"""
fix_jp2y_final.py — JP2Y series definitive fix
Checks what's in the server, shows it, then patches correctly.
Run: python src/execution/fix_jp2y_final.py
"""
from pathlib import Path
import sys, re

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

# ── Diagnose current state ────────────────────────────────────────────────
print("=== DIAGNOSIS ===")
print(f"jp2y_series in code: {'jp2y_series' in code}")
print(f"jp2y_series in fetch_usdjpy: ", end="")
idx = code.find("def fetch_usdjpy_yield_data")
uj_fn = code[idx:idx+3000] if idx > 0 else ""
print("jp2y_series" in uj_fn)

# Show the current return dict of fetch_usdjpy_yield_data
ret_idx = code.find('"current_z"', idx) if idx > 0 else -1
if ret_idx > 0:
    print("\nCurrent return dict keys:")
    block = code[ret_idx:ret_idx+800]
    for line in block.split('\n')[:25]:
        print(" ", line)

# ── Remove any previous broken jp2y_series attempts ─────────────────────
# Remove from fetch_yield_data if present
broken = '''    # ── 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 broken in code:
    code = code.replace(broken, "    return yields")
    print("\nRemoved broken jp2y from fetch_yield_data ✅")

# ── Now find the EXACT return statement in fetch_usdjpy_yield_data ────────
# Use regex to find the return dict and inject jp2y_series at the top
print("\n=== APPLYING FIX ===")

# Find the return { ... } block inside fetch_usdjpy_yield_data
# Look for "current_z": as the first key — inject jp2y_series before it
JP2Y_SERIES_CODE = '''            "jp2y_series": [
                {"date": str(d.date()), "jp2y": round(float(v), 4)}
                for d, v in zip(rates.iloc[-365:].index,
                                rates.iloc[-365:]["jp2y"])
            ],
            '''

target = '"current_z":      round(current_z, 4),'

# Find target inside fetch_usdjpy_yield_data function only
fn_start = code.find("def fetch_usdjpy_yield_data")
fn_end   = code.find("\ndef ", fn_start + 10)
if fn_end < 0:
    fn_end = len(code)

fn_body = code[fn_start:fn_end]

if '"jp2y_series"' in fn_body:
    print("jp2y_series already in fetch_usdjpy_yield_data — checking format...")
    idx2 = fn_body.find('"jp2y_series"')
    print(fn_body[idx2:idx2+150])
elif target in fn_body:
    # Inject before "current_z"
    fn_body_new = fn_body.replace(target, JP2Y_SERIES_CODE + target, 1)
    code = code[:fn_start] + fn_body_new + code[fn_end:]
    print("jp2y_series injected into fetch_usdjpy_yield_data ✅")
else:
    # Try alternate key format
    alt_target = '"current_z": round(current_z, 4),'
    if alt_target in fn_body:
        fn_body_new = fn_body.replace(
            alt_target,
            JP2Y_SERIES_CODE.replace(
                '"current_z":      round(current_z, 4),',
                '"current_z": round(current_z, 4),'),
            1)
        code = code[:fn_start] + fn_body_new + code[fn_end:]
        print("jp2y_series injected (alt format) ✅")
    else:
        print("❌ Could not find return dict — showing function body:")
        print(fn_body[1500:2500])
        sys.exit(1)

# ── Verify ────────────────────────────────────────────────────────────────
fn_start2 = code.find("def fetch_usdjpy_yield_data")
fn_end2   = code.find("\ndef ", fn_start2 + 10)
fn_check  = code[fn_start2:fn_end2]
print(f"\njp2y_series in function after patch: {'jp2y_series' in fn_check}")

SERVER.write_text(code, encoding="utf-8")
print(f"Server saved ({len(code.splitlines())} lines)")
print("\n✅ Done — restart dashboard_server.py")
