"""
fix_jp2y_server.py
Moves jp2y_series into fetch_usdjpy_yield_data() return value
as [{date, jp2y}] objects — the format the dashboard JS expects.
Run: python src/execution/fix_jp2y_server.py
"""
from pathlib import Path
import sys

BASE_PATH = Path(__file__).resolve().parents[2]
SERVER = BASE_PATH / "src" / "execution" / "dashboard_server.py"
code = SERVER.read_text(encoding="utf-8")

# Step 1: Remove the broken jp2y block from fetch_yield_data()
# (the one added by add_jp2y_series.py — wrong location)
old_yields_jp2y = '''    # ── Build jp2y_series for chart (last 365 rows = daily FinanceFlow data) ──
    try:
        import csv as _csv2
        jp2y_path = BASE_PATH / "data" / "raw" / "rates" / "jp2y.csv"
        if jp2y_path.exists():
            rows = [r for r in _csv2.reader(open(jp2y_path))
                    if len(r) == 2 and r[1] not in (".", "", "VALUE", "jp2y")]
            if rows:
                yields["jp2y_daily"]  = float(rows[-1][1])
                yields["jp2y_date"]   = rows[-1][0]
                hist = rows[-365:]  # 365 = one year of daily data
                yields["jp2y_series"] = [round(float(r[1]), 3) for r in hist]
                yields["jp2y_times"]  = [r[0] for r in hist]
    except Exception as _e:
        pass

    return yields'''

if old_yields_jp2y in code:
    code = code.replace(old_yields_jp2y, '    return yields')
    print("Removed jp2y from fetch_yield_data() ✅")
else:
    print("jp2y block in fetch_yield_data() not found (may already be clean)")

# Step 2: Add jp2y_series into fetch_usdjpy_yield_data() return dict
# Find the return statement and add jp2y_series to it
old_uj_return = '''            "z_history": [
                {"date": str(d.date()), "z": round(float(z), 4)}
                for d, z in zip(recent.index, recent["zscore"])
            ],
            "spread_history": [
                {"date": str(d.date()), "spread":'''

if old_uj_return in code and 'jp2y_series' not in code:
    new_uj_return = '''            "jp2y_series": [
                {"date": str(d.date()), "jp2y": round(float(v), 4)}
                for d, v in zip(rates.iloc[-365:].index,
                                rates.iloc[-365:]["jp2y"])
            ],
            "z_history": [
                {"date": str(d.date()), "z": round(float(z), 4)}
                for d, z in zip(recent.index, recent["zscore"])
            ],
            "spread_history": [
                {"date": str(d.date()), "spread":'''
    code = code.replace(old_uj_return, new_uj_return, 1)
    print("Added jp2y_series to fetch_usdjpy_yield_data() return ✅")
elif 'jp2y_series' in code:
    print("jp2y_series already in fetch_usdjpy_yield_data()")
else:
    print("❌ Could not find return dict in fetch_usdjpy_yield_data()")
    # Show context
    idx = code.find('z_history')
    print(repr(code[idx-50:idx+200]))
    sys.exit(1)

SERVER.write_text(code, encoding="utf-8")
print("Server patched ✅ | Restart dashboard_server.py to apply")
