#!/usr/bin/env python3
"""
patch_ftmo_hero.py
==================
Fixes the false FTMO hero numbers on the dashboard (100% / 1.7m from the broken
v1 sim) and replaces them with the real v4 results, plus adds a notional toggle
($300k / $150k / $100k). Default = $300k (current live sizing).

v4 results (FTMO 2-Step Swing $100k, real intraday floating DD from 15M bars):
  300k: pass 73-85%, median 1.4-2.9mo, daily-DD fail 9-17%
  150k: pass 91-95%, median 3.0-5.9mo, daily-DD fail 3-6%
  100k: pass 92-97%, median 4.6-8.5mo, daily-DD fail 2-3%

Changes:
  1) Give the two FTMO hero cells (Pass Rate, Median) IDs + hint IDs.
  2) Insert a small notional toggle just before the hero-row (or after header).
  3) Inject JS: FTMO_BY_NOTIONAL data + setFtmoNotional(), default 300k.

Tolerant exact-match; backs up; verifies replacements occurred.
"""
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"),
]
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_ftmohero")
if not backup.exists():
    shutil.copy2(target, backup); print(f"Backup: {backup}")
else:
    print(f"Backup exists: {backup}")

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

if "FTMO_BY_NOTIONAL" in html:
    print("Already applied. Nothing to do."); sys.exit(0)

# ---- 1) Pass Rate cell: add id, change to default 300k value ----
old_pass='''    <div class="h-lbl">FTMO Pass Rate</div>
    <div class="h-val v-green">100%</div>
    <div class="h-hint">5,000 MC sims Â· 0% breach</div>'''
new_pass='''    <div class="h-lbl">FTMO Pass Rate</div>
    <div class="h-val v-amber" id="hero-ftmo-pass">73-85%</div>
    <div class="h-hint" id="hero-ftmo-pass-hint">v4 real-cost Â· $300k/pair Â· 2-step swing</div>'''

# The hint uses a mojibake middot (Â·) in the file; match flexibly by trying both
def try_replace(h, old, new, label):
    if old in h:
        return h.replace(old, new, 1), True
    # try with plain middot
    old2=old.replace("Â·","·")
    if old2 in h:
        return h.replace(old2, new.replace("Â·","·"), 1), True
    return h, False

html, ok_pass = try_replace(html, old_pass, new_pass, "pass")

# ---- 2) Median cell ----
# We saw the label; need to handle its value/hint. Match on label then the next
# two lines generically is risky, so match the known full block.
old_med='''    <div class="h-lbl">Median Challenge Time</div>
    <div class="h-val v-amber">1.7m</div>
    <div class="h-hint">Combined model Â· P25=1.3m</div>'''
new_med='''    <div class="h-lbl">Median Challenge Time</div>
    <div class="h-val v-amber" id="hero-ftmo-med">1.4-2.9m</div>
    <div class="h-hint" id="hero-ftmo-med-hint">$300k/pair Â· range across methods</div>'''
html, ok_med = try_replace(html, old_med, new_med, "med")

# ---- 3) Insert toggle + JS. Put the toggle right before <div class="hero-row"> ----
toggle_html='''<div style="display:flex;gap:6px;align-items:center;margin:8px 0 4px 0;font-family:var(--mono)">
  <span style="font-size:9px;color:var(--muted);text-transform:uppercase;letter-spacing:.08em">FTMO Notional/pair:</span>
  <button class="ftmo-ntl-btn" data-ntl="300k" onclick="setFtmoNotional('300k')" style="font-size:9px;font-weight:700;padding:3px 9px;border-radius:4px;border:1px solid var(--border);background:rgba(0,232,122,.15);color:var(--green);cursor:pointer">$300k</button>
  <button class="ftmo-ntl-btn" data-ntl="150k" onclick="setFtmoNotional('150k')" style="font-size:9px;font-weight:700;padding:3px 9px;border-radius:4px;border:1px solid var(--border);background:transparent;color:var(--muted);cursor:pointer">$150k</button>
  <button class="ftmo-ntl-btn" data-ntl="100k" onclick="setFtmoNotional('100k')" style="font-size:9px;font-weight:700;padding:3px 9px;border-radius:4px;border:1px solid var(--border);background:transparent;color:var(--muted);cursor:pointer">$100k</button>
</div>
<div class="hero-row">'''
if '<div class="hero-row">' in html:
    html = html.replace('<div class="hero-row">', toggle_html, 1)
    ok_toggle=True
else:
    ok_toggle=False

# JS block — inject before the final </script> or before </body>
js='''
<script>
// FTMO v4 results (2-Step Swing $100k, real intraday floating DD from 15M bars, 2003-2026)
const FTMO_BY_NOTIONAL = {
  "300k": {pass:"73-85%", passClass:"v-amber", med:"1.4-2.9m",
           passHint:"v4 real-cost \\u00b7 $300k/pair \\u00b7 daily-DD 9-17%",
           medHint:"$300k/pair \\u00b7 fastest, ~1-in-5 fail"},
  "150k": {pass:"91-95%", passClass:"v-green", med:"3.0-5.9m",
           passHint:"v4 real-cost \\u00b7 $150k/pair \\u00b7 daily-DD 3-6%",
           medHint:"$150k/pair \\u00b7 balanced choice"},
  "100k": {pass:"92-97%", passClass:"v-green", med:"4.6-8.5m",
           passHint:"v4 real-cost \\u00b7 $100k/pair \\u00b7 daily-DD 2-3%",
           medHint:"$100k/pair \\u00b7 near-certain but slow"},
};
function setFtmoNotional(ntl){
  const d = FTMO_BY_NOTIONAL[ntl]; if(!d) return;
  const pv=document.getElementById('hero-ftmo-pass');
  const ph=document.getElementById('hero-ftmo-pass-hint');
  const mv=document.getElementById('hero-ftmo-med');
  const mh=document.getElementById('hero-ftmo-med-hint');
  if(pv){ pv.textContent=d.pass; pv.className='h-val '+d.passClass; }
  if(ph){ ph.textContent=d.passHint; }
  if(mv){ mv.textContent=d.med; }
  if(mh){ mh.textContent=d.medHint; }
  document.querySelectorAll('.ftmo-ntl-btn').forEach(function(b){
    const on = b.getAttribute('data-ntl')===ntl;
    b.style.background = on ? 'rgba(0,232,122,.15)' : 'transparent';
    b.style.color = on ? 'var(--green)' : 'var(--muted)';
  });
}
// initialise to 300k on load
document.addEventListener('DOMContentLoaded', function(){ setFtmoNotional('300k'); });
</script>
'''
if "</body>" in html:
    html = html.replace("</body>", js + "</body>", 1)
    ok_js=True
else:
    html = html + js
    ok_js=True

target.write_text(html, encoding="utf-8")
print(f"Pass cell updated : {ok_pass}")
print(f"Median cell updated: {ok_med}")
print(f"Toggle inserted   : {ok_toggle}")
print(f"JS injected       : {ok_js}")
if not (ok_pass and ok_med):
    print("\nWARN: one or both hero cells not matched exactly (mojibake/whitespace).")
    print("Send the exact hero block lines and I'll adjust. Backup is safe.")
else:
    print("\nSUCCESS - hard refresh dashboard (Ctrl+F5). Default shows $300k real numbers.")
