import pandas as pd
import requests
import json
import os
from io import StringIO
from datetime import datetime

BOND_TARGETS = {
    'KR600593000A': 'IRR_CORP03Y',
    'KR600538012C': 'IRR_CORP03Y',
    'KR610556011B': 'IRR_CORP03Y',
    'KR103501G000': 'IRR_GOVT03Y'
}

def fetch_naver_bond_yields():
    print("--- Fetching Representative Korean Bond Yields from Naver Finance ---")
    results = {}
    
    for ticker, naver_code in BOND_TARGETS.items():
        url = f"https://finance.naver.com/marketindex/interestDailyQuote.naver?marketindexCd={naver_code}"
        try:
            # Fake User-Agent to avoid 403 blocks
            response = requests.get(url, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'})
            
            # Using StringIO to suppress warnings about literal string parsing in pandas 2.2+
            df = pd.read_html(StringIO(response.text))[0]
            
            # Column 1 is usually the yield (0-indexed is Date, 1 is Yield)
            latest_yield = float(df.iloc[0, 1])
            results[ticker] = latest_yield
            print(f"Scraped {ticker}: {latest_yield}%")
            
        except Exception as e:
            print(f"Failed to fetch {ticker}: {e}")
            results[ticker] = 0.0

    # Save to JSON
    os.makedirs('C:/Users/Variet-Worker/Desktop/climate_risk/data', exist_ok=True)
    out_path = 'C:/Users/Variet-Worker/Desktop/climate_risk/data/live_bond_yields.json'
    
    with open(out_path, 'w') as f:
        json.dump({'date': datetime.now().strftime('%Y-%m-%d'), 'yields': results}, f, indent=4)
        
    print(f"Saved yields to {out_path}")

if __name__ == '__main__':
    fetch_naver_bond_yields()
