"""
add_jp2y_series.py
Adds jp2y_series to fetch_yield_data() in dashboard_server.py.
Run: python src/execution/add_jp2y_series.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")

# Insert jp2y section after sofr_series block, before return yields
old = '    return yields'

new = '''    # ── 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 'jp2y_series' in code:
    print("jp2y_series already present in dashboard_server.py")
elif old in code:
    code = code.replace(old, new, 1)
    SERVER.write_text(code, encoding="utf-8")
    print("jp2y_series added to fetch_yield_data() ✅")
    print("Restart dashboard_server.py to apply.")
else:
    print("ERROR: 'return yields' not found in fetch_yield_data()")
    sys.exit(1)
