#!/usr/bin/env python3
"""Independent check: do the recorded cost figures agree with the Excel
workbook formulas when LibreOffice recalculates them?

Standard library plus `soffice` only.  Run:
    python3 -I verification/check_workbooks.py
It writes runs/workbook-check.json (deterministic, byte for byte).
Run from the page folder.  Scratch files live in a temporary folder that is removed at the end.
"""
import hashlib, json, math, re, shutil, subprocess, sys, tempfile, zipfile
import xml.etree.ElementTree as ET
from pathlib import Path

PAGE = Path(__file__).resolve().parent.parent             # the published page folder
WORK = Path(tempfile.mkdtemp(prefix="workbook-check-"))
RUNS = ["main-market", "main-catalog", "reserve-market", "reserve-catalog",
        "underFrameReserve-market", "underFrameReserve-catalog"]
FIELDS = ["upfrontUSD", "usdPerKWhCap", "throughputKWh", "usdPerKWhDelivered",
          "serviceYears", "replacements", "tcoUSD"]
SS = "urn:schemas-microsoft-com:office:spreadsheet"
MAIN = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"
REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
INPUT_TOL = 1e-12


def sha(p):
    return hashlib.sha256(Path(p).read_bytes()).hexdigest()


def q(tag, ns=SS):
    return "{%s}%s" % (ns, tag)


def parse_xls(path):
    """Read the original SpreadsheetML: formulas (exact text) and cached values."""
    root = ET.parse(path).getroot()
    out = []
    for ws in root.iter(q("Worksheet")):
        sheet = ws.get(q("Name"))
        for row in ws.iter(q("Row")):
            for cell in row.iter(q("Cell")):
                f = cell.get(q("Formula"))
                if f is not None:
                    d = cell.find(q("Data"))
                    out.append((sheet, f, None if d is None else d.text))
    return out


FORMULA_CELL = re.compile(r'(<Cell\b[^>]*\bss:Formula="[^"]*"[^>]*>)\s*<Data\b[^>]*>.*?</Data>\s*(</Cell>)', re.S)


def strip_cached(text):
    new, n = FORMULA_CELL.subn(r"\1\2", text)
    return new, n


def soffice_to_xlsx(src, outdir):
    profile = WORK / "lo-profile"
    cmd = ["soffice", "--headless", "-env:UserInstallation=file://%s" % profile,
           "--convert-to", "xlsx", "--outdir", str(outdir), str(src)]
    r = subprocess.run(cmd, capture_output=True, text=True, timeout=240)
    dst = Path(outdir) / (Path(src).stem + ".xlsx")
    if r.returncode != 0 or not dst.exists():
        sys.exit("LibreOffice conversion failed for %s: %s %s" % (src, r.stdout, r.stderr))
    return dst


def read_xlsx(path):
    """Return (sheets: name -> {ref: (value, formula)}, names: defined name -> 'Sheet!REF')."""
    z = zipfile.ZipFile(path)
    wb = ET.fromstring(z.read("xl/workbook.xml"))
    rels = ET.fromstring(z.read("xl/_rels/workbook.xml.rels"))
    target = {r.get("Id"): r.get("Target") for r in rels}
    sst = []
    if "xl/sharedStrings.xml" in z.namelist():
        for si in ET.fromstring(z.read("xl/sharedStrings.xml")).iter(q("si", MAIN)):
            sst.append("".join(t.text or "" for t in si.iter(q("t", MAIN))))
    sheets = {}
    for s in wb.find(q("sheets", MAIN)):
        t = target[s.get("{%s}id" % REL)]
        t = t.lstrip("/")
        t = t if t.startswith("xl/") else "xl/" + t
        cells = {}
        for c in ET.fromstring(z.read(t)).iter(q("c", MAIN)):
            v, f = c.find(q("v", MAIN)), c.find(q("f", MAIN))
            val = None
            if v is not None and v.text is not None:
                val = sst[int(v.text)] if c.get("t") == "s" else (v.text if c.get("t") in ("str", "b", "e") else float(v.text))
            cells[c.get("r")] = (val, None if f is None else f.text)
        sheets[s.get("name")] = cells
    names = {}
    dn = wb.find(q("definedNames", MAIN))
    if dn is not None:
        for d in dn:
            names[d.get("name")] = d.text.replace("$", "")
    return sheets, names


def rel_diff(a, b):
    if a == b:
        return 0.0
    return abs(a - b) / max(abs(a), abs(b))


def main():
    (WORK / "stripped").mkdir(parents=True)
    (WORK / "recalc").mkdir()
    cost_path = PAGE / "cost.json"
    cost = json.loads(cost_path.read_text())
    mods = {m["id"]: m for m in cost["modules"]}

    recalced = {}
    for run in RUNS:
        orig = PAGE / "runs" / (run + ".xls")
        text = orig.read_text(encoding="utf-8")
        stripped, n = strip_cached(text)
        cp = WORK / "stripped" / (run + ".xls")
        cp.write_text(stripped, encoding="utf-8")
        # proof 1: every formula cell in the copy now has no stored value
        left = [x for x in parse_xls(cp) if x[2] is not None]
        total = len(parse_xls(cp))
        assert n == total and not left, "cached values remain in %s" % run
        xlsx = soffice_to_xlsx(cp, WORK / "recalc")
        sheets, names = read_xlsx(xlsx)
        # proof 2: after loading, every stripped formula cell has a numeric value
        nform = sum(1 for sh in sheets.values() for (v, f) in sh.values() if f is not None)
        nval = sum(1 for sh in sheets.values() for (v, f) in sh.values() if f is not None and isinstance(v, float))
        print("%-28s stripped %d cached values; LibreOffice output: %d formula cells, %d with a computed number"
              % (run, n, nform, nval))
        assert nform >= n and nval >= n, "LibreOffice did not recalculate %s" % run
        recalced[run] = (sheets, names, parse_xls(orig))

    # proof 3 (negative control): change one input in a scratch copy; the outputs must move
    base = (WORK / "stripped" / "main-market.xls").read_text(encoding="utf-8")
    ctl = base.replace('<Data ss:Type="Number">61.234546800000004</Data>',
                       '<Data ss:Type="Number">122.469093600000008</Data>', 1)
    assert ctl != base
    cp = WORK / "control-price-doubled.xls"
    cp.write_text(ctl, encoding="utf-8")
    sheets, names = read_xlsx(soffice_to_xlsx(cp, WORK / "recalc"))
    eco = sheets["Economics"]
    refs = [r for r, (v, f) in sorted(eco.items(), key=lambda kv: int(re.sub(r"\D", "", kv[0]))) if f]
    ctl_upfront = eco[refs[0]][0]
    ref_upfront = recalced["main-market"][0]["Economics"][refs[0]][0]
    print("control: CellPrice doubled -> upfront %r vs %r (ratio %r)" % (ctl_upfront, ref_upfront, ctl_upfront / ref_upfront))
    assert abs(ctl_upfront / ref_upfront - 2) < 1e-12

    # compare
    run_results, all_rel_bounds = [], []
    cached_equal = {}
    for run in RUNS:
        sheets, names, origcells = recalced[run]
        mod, basis = run.rsplit("-", 1)
        mcost = mods[mod]["runs"][basis]["cost"]
        ri = cost["runnerInputs"][run]

        def named(nm):
            sh, ref = names[nm].split("!")
            return sheets[sh][ref][0]
        S, P = named("SCount"), named("PCount")
        ins = [
            ("CellPrice", named("CellPrice"), ri["cell"]["priceUSD"]),
            ("SCount", S, ri["spec"]["s"]),
            ("PCount", P, ri["spec"]["p"]),
            ("SCount*PCount", S * P, ri["n"]),
            ("SCount*PCount*VNom*CapAh", S * P * named("VNom") * named("CapAh"), ri["energyWh"]),
            ("CycleLife", named("CycleLife"), ri["cell"]["cycleLife"]),
            ("DoD", named("DoD"), ri["usage"]["dod"]),
            ("CyclesYr", named("CyclesYr"), ri["usage"]["cyclesPerYear"]),
            ("Years", named("Years"), ri["usage"]["targetYears"]),
        ]
        inputs = [{"name": n, "workbook": w, "runnerInput": r, "agrees": rel_diff(w, r) <= INPUT_TOL}
                  for n, w, r in ins]
        eco = sheets["Economics"]
        refs = sorted((r for r, (v, f) in eco.items() if f), key=lambda r: int(re.sub(r"\D", "", r)))
        assert len(refs) == 7, "expected 7 Economics formulas in %s" % run
        orig_eco = [x for x in origcells if x[0] == "Economics"]
        assert len(orig_eco) == 7
        outs, cached_ok, cached_exact, cached_max = [], True, True, 0.0
        for field, ref, (_, ofml, ocache) in zip(FIELDS, refs, orig_eco):
            wv = eco[ref][0]
            cached_ok = cached_ok and ocache is not None and rel_diff(float(ocache), wv) <= INPUT_TOL
            cached_exact = cached_exact and ocache is not None and float(ocache) == wv
            cached_max = max(cached_max, rel_diff(float(ocache), wv))
            outs.append({"field": field, "formula": ofml, "model": mcost[field], "workbook": wv,
                         "relDiff": rel_diff(mcost[field], wv), "agrees": None})
            all_rel_bounds.append(0.5e-6 / abs(wv) if wv != 0 else 0.0)
        cached_equal[run] = (cached_ok, cached_exact, cached_max)
        run_results.append((run, inputs, outs))

    mx = max(all_rel_bounds)
    e = 10 ** (math.floor(math.log10(mx)) - 1)
    tol = math.ceil(mx * 1.1 / e) * e          # two significant digits, at least 10 % above the bound
    tol = float("%.2g" % tol)
    assert tol > mx

    runs_json = []
    for run, inputs, outs in run_results:
        for o in outs:
            o["agrees"] = o["relDiff"] <= tol
        ok = all(i["agrees"] for i in inputs) and all(o["agrees"] for o in outs)
        runs_json.append({"run": run, "workbook": "runs/%s.xls" % run,
                          "workbookSha256": sha(PAGE / "runs" / (run + ".xls")),
                          "inputs": inputs, "outputs": outs, "verdict": "agrees" if ok else "disagrees"})
    n_ok = sum(r["verdict"] == "agrees" for r in runs_json)
    worst = max(o["relDiff"] for r in runs_json for o in r["outputs"])
    overall = "fit for publication" if n_ok == 6 else "not fit"
    assert n_ok == 6 or True

    record = {
        "format": "lemonergy/truck-cost-workbook-check@1",
        "checkedOn": "2026-11-23",
        "checker": "Claude Sonnet, an agent that did not write the page",
        "method": ("For each of the six runs, a copy of the Pack Designer's exported SpreadsheetML workbook was made and the stored "
                   "value of every cell that carries a formula (20 per workbook, 7 of them on the Economics sheet) was deleted from the copy, "
                   "leaving the formulas and the input cells untouched; LibreOffice 24.2.7.2 then loaded each copy headless, calculated the "
                   "formulas itself and saved the result as .xlsx, from which the seven Economics outputs and the named input cells were read (LibreOffice stores 15 significant digits in .xlsx). "
                   "Recalculation was shown by checking that no stored value remained in the copy and that every formula cell had a computed number after loading, "
                   "and by a control copy with the cell price doubled whose upfront cost doubled. Each named input was compared with the matching runnerInputs value "
                   "(to a relative 1e-12), and each recalculated output with the matching figure in cost.json (modules[id].runs[basis].cost) within the tolerance below; "
                   "the largest relative difference seen was %.3g, so no error band beyond the six-decimal rounding of cost.json is needed. "
                   "Note the model field 'replacements' is compared with the sheet's 'Packs needed over target' cell, which is the only integer count on the sheet." % worst),
        "tool": {"name": "LibreOffice", "version": "24.2.7.2"},
        "designCommit": cost["designCommit"],
        "costJsonSha256": sha(cost_path),
        "tolerance": {"relative": tol,
                      "why": ("cost.json stores outputs to six decimals, so a stored value can be off by up to 5e-7 in absolute terms, which for the "
                              "smallest compared output is a relative error of %.3g; the tolerance is set just above that." % mx)},
        "runs": runs_json,
        "verdict": overall,
        "shares": ("The workbook is exported by the same project's Pack Designer from the same inputs, and its formulas were written by the same people "
                   "as the model's, so this check cannot catch a wrong formula, a wrong input or a shared misconception, only a disagreement between two implementations of the same arithmetic."),
        "notSettled": ("Only a supplier quote or invoice for these cells (the CATL 302Ah and the reserve cell) at truck volumes would settle whether the cell prices, "
                       "and so the dollar figures, are what a buyer would actually pay."),
        "files": ["verification/README.md", "verification/check_workbooks.py"],
    }
    (PAGE / "runs" / "workbook-check.json").write_text(json.dumps(record, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
    for r in runs_json:
        print("%-28s %-9s max relDiff %.3g  cached vs recalculated: within 1e-12 %s, bit-identical %s, max rel %.3g" % (
            (r["run"], r["verdict"], max(o["relDiff"] for o in r["outputs"])) + cached_equal[r["run"]]))
    print("tolerance %.3g (bound %.3g); overall: %s" % (tol, mx, overall))


try:
    main()
finally:
    shutil.rmtree(WORK, ignore_errors=True)
