"""
fix_jp2y_server_v2.py
Adds jp2y_series to fetch_usdjpy_yield_data() return.
Prints diagnosis first, then patches.
Run: python src/execution/fix_jp2y_server_v2.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")

print("=== DIAGNOSIS ===")
fn_start = code.find("def fetch_usdjpy_yield_data")
if fn_start < 0:
    print("ERROR: fetch_usdjpy_yield_data not found"); sys.exit(1)

fn_end = code.find("\ndef ", fn_start + 10)
if fn_end < 0: fn_end = len(code)
fn = code[fn_start:fn_end]

print(f"Function found at char {fn_start}")
print(f"jp2y_series already present: {'jp2y_series' in fn}")

if "jp2y_series" in fn:
    print("Already patched — showing current jp2y_series block:")
    idx = fn.find("jp2y_series")
    print(fn[idx:idx+200])
    sys.exit(0)

print()
print("=== PATCHING ===")

# Find 'return {' inside the function — inject jp2y_series as first key
# Use the 'rates' dataframe which is already built in the function
return_idx = fn.rfind("return {")
if return_idx < 0:
    print("ERROR: could not find 'return {' in function")
    print("Function tail:")
    print(fn[-1000:])
    sys.exit(1)

print(f"Found 'return {{' at position {return_idx} within function")
print("Context:")
print(fn[return_idx:return_idx+100])

# Build the injection — insert jp2y_series right after 'return {'
jp2y_inject = """            "jp2y_series": [
                {"date": str(d.date()), "jp2y": round(float(v), 4)}
                for d, v in zip(rates.iloc[-365:].index,
                                rates.iloc[-365:]["jp2y"])
            ],
"""

# Find the exact position in the full code
abs_return_pos = fn_start + return_idx
# Find the newline after 'return {'
newline_after = code.find("\n", abs_return_pos + len("return {"))
if newline_after < 0:
    print("ERROR: could not find newline after return {")
    sys.exit(1)

code = code[:newline_after+1] + jp2y_inject + code[newline_after+1:]

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

if "jp2y_series" in fn2:
    SERVER.write_text(code, encoding="utf-8")
    print(f"Saved ({len(code.splitlines())} lines) ✅")
    print("Restart dashboard_server.py to apply")
else:
    print("ERROR: patch did not apply — not saving")
    sys.exit(1)
