#!/usr/bin/env python3
"""
patch_heatmap_frontend.py
=========================
Replaces the dashboard.html block that partially overrode only EU 2026 with
a full override: every year of BOTH EU_MONTHLY and UJ_MONTHLY is overwritten
from the server's real per-pair data (heatmap_eu_all / heatmap_uj_all), then
combined is rebuilt. This makes the hardcoded arrays dead/ignored — real data
shows on every load.

Matches the exact existing block (dash-free lines only) and replaces it.
Backs up first; this is HTML so no python-syntax check, but we verify the
replacement happened and brace/paren balance is unchanged.
Usage: python patch_heatmap_frontend.py
"""
import sys, shutil
from pathlib import Path

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

backup = target.with_suffix(".html.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)

# The exact existing block — dash-free lines. We match the core JS, which is
# stable regardless of the comment line above it (which has box-drawing chars).
old = """  if(d.heatmap_2026){
    EU_MONTHLY['2026']=d.heatmap_2026;
    // Recompute combined 2026 row
    const uj2026=UJ_MONTHLY['2026']||Array(12).fill(0);
    CO_MONTHLY['2026']=d.heatmap_2026.map((v,i)=>{
      const u=uj2026[i];
      if(v===null&&u===null)return null;
      return(v||0)+(u||0);
    });
    buildHeatmap();
  }"""

new = """  // Full real per-pair heatmap override (backtest + live) from server.
  // Overwrites every year of EU_MONTHLY and UJ_MONTHLY with verified real
  // data, making the hardcoded arrays irrelevant. Then rebuilds combined.
  if(d.heatmap_eu_all){
    Object.keys(d.heatmap_eu_all).forEach(function(yr){
      EU_MONTHLY[yr]=d.heatmap_eu_all[yr];
    });
  }
  if(d.heatmap_uj_all){
    Object.keys(d.heatmap_uj_all).forEach(function(yr){
      UJ_MONTHLY[yr]=d.heatmap_uj_all[yr];
    });
  }
  if(d.heatmap_eu_all||d.heatmap_uj_all){
    CO_MONTHLY=buildCombined();
    buildHeatmap();
  } else if(d.heatmap_2026){
    // Legacy fallback (only if server has no heatmap_data.json yet)
    EU_MONTHLY['2026']=d.heatmap_2026;
    const uj2026=UJ_MONTHLY['2026']||Array(12).fill(0);
    CO_MONTHLY['2026']=d.heatmap_2026.map(function(v,i){
      const u=uj2026[i];
      if(v===null&&u===null)return null;
      return(v||0)+(u||0);
    });
    buildHeatmap();
  }"""

count = content.count(old)
if count == 1:
    content = content.replace(old, new)
    print("PATCH applied: full per-pair override block installed")
elif count == 0:
    print("ERROR: could not find the exact existing block to replace.")
    print("The block may have different whitespace. No changes written.")
    print("Send the dashboard.html heatmap block and I'll adjust the matcher.")
    sys.exit(2)
else:
    print(f"ERROR: block found {count} times (expected 1). Aborting.")
    sys.exit(2)

# Brace/paren sanity: counts should remain balanced
for ch_open, ch_close in [("{","}"), ("(",")"), ("[","]")]:
    if content.count(ch_open) != content.count(ch_close):
        print(f"WARNING: '{ch_open}{ch_close}' unbalanced after patch "
              f"({content.count(ch_open)} vs {content.count(ch_close)}). "
              f"Review before trusting. Writing anyway since this can be "
              f"pre-existing in HTML/CSS.")

target.write_text(content, encoding="utf-8")
print("SUCCESS")
print("\nNext: refresh the dashboard in your browser (hard refresh Ctrl+F5).")
print("Toggle EU / UJ / Combined — all should show real backtest+live data.")
