#!/usr/bin/env python3
"""Check that dashboard.html and model.py compute the same numbers.

Extracts the <script id="model"> block from dashboard.html, runs it in Node
for every preset, and compares every numeric output with model.py.
Run:  python3 check_dashboard.py      (needs node on PATH; stdlib only)
"""
import json
import math
import os
import re
import shutil
import subprocess
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import model  # noqa: E402

TOL = 1e-9
EDGE_CASES = {  # guards: zero volume, zero rates, tier shares over 100%, zero hourly value
    "edge_zero_emails": {"emails": 0},
    "edge_zero_rates": {"open": 0, "reply": 0, "sample": 0, "paid": 0, "repeat": 0},
    "edge_mix_over_100": {"mix3": 0.8, "mix5": 0.6},
    "edge_zero_hourly": {"hourly": 0, "min_per_ad": 0},
    "edge_reply_above_open": {"open": 0.01, "reply": 0.05},
}


def flatten(obj, prefix=""):
    if isinstance(obj, dict):
        for k, v in obj.items():
            yield from flatten(v, f"{prefix}.{k}" if prefix else k)
    elif isinstance(obj, (list, tuple)):
        for i, v in enumerate(obj):
            yield from flatten(v, f"{prefix}[{i}]")
    else:
        yield prefix, obj


def main():
    print("[1/4] Reading model block from dashboard.html ...", flush=True)
    html = open(os.path.join(HERE, "dashboard.html"), encoding="utf-8").read()
    m = re.search(r'<script id="model">(.*?)</script>', html, re.S)
    if not m:
        print("FAIL: no <script id=\"model\"> block found")
        return 1
    if not shutil.which("node"):
        print("FAIL: node not found on PATH")
        return 1
    harness = m.group(1) + """
const out = {};
for (const name of Object.keys(PRESETS)) out[name] = compute(Object.assign({}, OPERATING, PRESETS[name]));
const EDGE = %s;
for (const name of Object.keys(EDGE)) out[name] = compute(Object.assign({}, OPERATING, PRESETS.base, EDGE[name]));
out.__constants = {PRICES, OPERATING, PRESETS, LAG_PAID, LAG_REPEAT, WEEKS, TARGET_MONTHLY, TOOL_COST_PER_WEEK};
process.stdout.write(JSON.stringify(out));
""" % json.dumps(EDGE_CASES)
    print("[2/4] Running it in Node ...", flush=True)
    js = json.loads(subprocess.run(["node", "-"], input=harness, capture_output=True, text=True, check=True).stdout)

    print("[3/4] Comparing constants ...", flush=True)
    py_const = {"PRICES": {str(k): v for k, v in model.PRICES.items()}, "OPERATING": model.OPERATING,
                "PRESETS": model.PRESETS, "LAG_PAID": model.LAG_PAID, "LAG_REPEAT": model.LAG_REPEAT,
                "WEEKS": model.WEEKS, "TARGET_MONTHLY": model.TARGET_MONTHLY,
                "TOOL_COST_PER_WEEK": model.TOOL_COST_PER_WEEK}
    const_ok = json.dumps(py_const, sort_keys=True) == json.dumps(js["__constants"], sort_keys=True)
    print(f"      constants identical: {const_ok}")

    print("[4/4] Comparing outputs per preset ...", flush=True)
    failures, checked = 0, 0
    for name in list(model.PRESETS) + list(EDGE_CASES):
        inp = {**model.inputs_for("base"), **EDGE_CASES[name]} if name in EDGE_CASES else model.inputs_for(name)
        py = model.compute(inp)
        jsr = dict(js[name])
        jsr.pop("mix_scaled", None)
        py_flat, js_flat = dict(flatten(py)), dict(flatten(jsr))
        if set(py_flat) != set(js_flat):
            print(f"      {name}: key mismatch {sorted(set(py_flat) ^ set(js_flat))}")
            failures += 1
            continue
        worst = 0.0
        for k, a in py_flat.items():
            b = js_flat[k]
            checked += 1
            if a is None or b is None:
                if a is not b:
                    print(f"      {name}.{k}: python={a} js={b}")
                    failures += 1
                continue
            if isinstance(a, float) and not math.isfinite(a):
                print(f"      {name}.{k}: not finite ({a})")
                failures += 1
                continue
            diff = abs(float(a) - float(b))
            worst = max(worst, diff)
            if diff > TOL * max(1.0, abs(float(a))):
                print(f"      {name}.{k}: python={a} js={b}")
                failures += 1
        print(f"      {name:<22} {len(py_flat)} values, largest difference {worst:.2e}")
    base_py = model.compute(model.inputs_for("base"))
    print(f"      Base monthly revenue: python ${base_py['monthly_revenue']:.6f} | js ${js['base']['monthly_revenue']:.6f}")
    print(f"      Base emails for $1,000/month: python {base_py['emails_needed']} | js {js['base']['emails_needed']}")
    print(f"      Base cost to win a client: python ${base_py['cac']:.6f} | js ${js['base']['cac']:.6f}")
    ok = const_ok and failures == 0
    print(f"RESULT: {'PASS' if ok else 'FAIL'} ({checked} values compared, {failures} mismatches)")
    return 0 if ok else 1


if __name__ == "__main__":
    sys.exit(main())
