#!/usr/bin/env python3
"""
patch_heatmap_server.py
=======================
Adds real per-pair heatmap data to the dashboard server payload by reading
data/logs/heatmap_data.json (produced by build_heatmap_data.py).

Inserts, right after the existing `data["heatmap_2026"] = ...` assignment,
a block that attaches full per-pair real data:
    data["heatmap_eu_all"]   = {...all years...}
    data["heatmap_uj_all"]   = {...all years...}
    data["heatmap_cutover"]  = "2026-04"

Tolerant line-based matching; verifies syntax; backs up first.
Usage: python patch_heatmap_server.py
"""
import sys, shutil, ast
from pathlib import Path

candidates = [
    Path(r"C:\Users\paul_\OneDrive\fx_macro_intraday\src\execution\dashboard_server.py"),
    Path(r"C:\Users\Administrator\OneDrive\fx_macro_intraday\src\execution\dashboard_server.py"),
    Path(__file__).parent / "dashboard_server.py",
]
target = next((p for p in candidates if p.exists()), None)
if target is None:
    print("ERROR: dashboard_server.py not found")
    sys.exit(1)
print(f"Target: {target}")

backup = target.with_suffix(".py.backup_heatmap")
if not backup.exists():
    shutil.copy2(target, backup)
    print(f"Backup: {backup}")
else:
    print(f"Backup already exists: {backup}")

content = target.read_text(encoding="utf-8")

if "heatmap_eu_all" in content:
    print("Already applied (found heatmap_eu_all). Nothing to do.")
    sys.exit(0)

lines = content.splitlines(keepends=True)

# Find the line that assigns data["heatmap_2026"] = monthly_2026
anchor_idx = None
for i, ln in enumerate(lines):
    s = ln.strip()
    if s.startswith('data["heatmap_2026"]') and "monthly_2026" in s:
        anchor_idx = i
        break

if anchor_idx is None:
    print("ERROR: could not find data[\"heatmap_2026\"] = monthly_2026 anchor.")
    sys.exit(2)

indent = lines[anchor_idx][:len(lines[anchor_idx]) - len(lines[anchor_idx].lstrip())]

block = (
    f"{indent}# Real per-pair heatmap data (backtest + live) from heatmap_data.json\n"
    f"{indent}# Built by build_heatmap_data.py. Overrides the front-end's\n"
    f"{indent}# hardcoded arrays with verified real numbers on every load.\n"
    f"{indent}try:\n"
    f"{indent}    import json as _json_hm\n"
    f"{indent}    _hm_path = BASE_PATH / 'data' / 'logs' / 'heatmap_data.json'\n"
    f"{indent}    _hm = _json_hm.loads(_hm_path.read_text(encoding='utf-8'))\n"
    f"{indent}    data['heatmap_eu_all']  = _hm.get('eurusd', {{}})\n"
    f"{indent}    data['heatmap_uj_all']  = _hm.get('usdjpy', {{}})\n"
    f"{indent}    data['heatmap_cutover'] = _hm.get('cutover_month', '2026-04')\n"
    f"{indent}except Exception as _hm_e:\n"
    f"{indent}    data['heatmap_eu_all']  = None\n"
    f"{indent}    data['heatmap_uj_all']  = None\n"
)

# Insert AFTER the anchor line
lines.insert(anchor_idx + 1, block)
content = "".join(lines)

try:
    ast.parse(content)
    print("Syntax check: OK")
except SyntaxError as e:
    print(f"ERROR: syntax error: {e}. Aborting, no changes written.")
    sys.exit(3)

target.write_text(content, encoding="utf-8")
print("PATCH applied: server now emits heatmap_eu_all / heatmap_uj_all")
print("SUCCESS")
