#!/usr/bin/env python3
"""Release validation for the Mining Capacity Standard workbook.

Steps: (1) LibreOffice headless full recalculation and formula-error scan; (2) independent engine comparison (capacity_engine.py --xlsx);
(3) Checks sheet tally (ERROR / WARN / PASS); (4) stamp Version_Log (recalc, engine, checks, verdict, timestamp) and write a Markdown log.

Usage: python3 -I validate_capacity.py <workbook.xlsx> [--inputs inputs.json] [--log validation_log.md] [--recalc-script /mnt/skills/public/xlsx/scripts/recalc.py]
"""
import sys, os, json, subprocess, argparse, datetime, shutil
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import capacity_common as cc
import capacity_engine as eng
from openpyxl import load_workbook

def libreoffice_recalc(path, recalc_script):
    if recalc_script and os.path.exists(recalc_script):
        out = subprocess.run([sys.executable, recalc_script, path, "180"], capture_output=True, text=True)
        try:
            j = json.loads(out.stdout[out.stdout.find("{"):])
            return j.get("status") == "success", j.get("total_formulas"), j.get("total_errors"), j
        except Exception:
            return False, None, None, {"raw": out.stdout + out.stderr}
    # fallback: soffice convert in place (recalculates on load/save) then scan for error strings
    tmpdir = os.path.join(os.path.dirname(os.path.abspath(path)), "_recalc_tmp"); os.makedirs(tmpdir, exist_ok=True)
    subprocess.run(["soffice", "--headless", "--calc", "--convert-to", "xlsx", "--outdir", tmpdir, path], capture_output=True, text=True, timeout=300)
    conv = os.path.join(tmpdir, os.path.basename(path))
    if os.path.exists(conv): shutil.move(conv, path)
    wb = load_workbook(path, data_only=True); wbf = load_workbook(path)
    n_f = sum(1 for ws in wbf.worksheets for row in ws.iter_rows() for c in row if isinstance(c.value, str) and c.value.startswith("="))
    errs = [f"{ws.title}!{c.coordinate}" for ws in wb.worksheets for row in ws.iter_rows() for c in row if isinstance(c.value, str) and c.value.startswith("#") and c.value.endswith(("!", "?", "0", "A"))]
    return len(errs) == 0, n_f, len(errs), {"locations": errs[:20]}

def tally_checks(path):
    wb = load_workbook(path, data_only=True); ws = wb["Checks"]
    vals = [ws.cell(r, 4).value for r in range(5, ws.max_row + 1) if ws.cell(r, 2).value and ws.cell(r, 1).value is not None]
    return vals.count("PASS"), vals.count("WARN"), vals.count("ERROR"), [(ws.cell(r, 2).value, ws.cell(r, 3).value) for r in range(5, ws.max_row + 1) if ws.cell(r, 4).value == "WARN"]

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("xlsx"); ap.add_argument("--inputs"); ap.add_argument("--log", default="validation_log.md")
    ap.add_argument("--recalc-script", default="/mnt/skills/public/xlsx/scripts/recalc.py")
    a = ap.parse_args()
    companies, spot = (eng.load_inputs(a.inputs)[:2] if a.inputs else (cc.COMPANIES, cc.PARAMS["btc_spot_usd"]))
    fp = cc.fingerprint(eng.load_inputs(a.inputs)[2]) if a.inputs else cc.fingerprint()

    ok_rc, n_f, n_err, _ = libreoffice_recalc(a.xlsx, a.recalc_script)
    rc_txt = f"{'success' if ok_rc else 'FAILED'} — {n_f} formulas, {n_err} errors"
    n_ok, n_bad, bad = eng.compare_xlsx(a.xlsx, companies, spot)
    eng_txt = f"{n_ok + n_bad} derived values, {n_ok} match, {n_bad} mismatch — {'OK' if n_bad == 0 else 'MISMATCH'}"
    # stamp provisional engine/recalc so the Checks sheet can reference them, then recalc again for the tally
    wb = load_workbook(a.xlsx); vl = wb["Version_Log"]
    stamp = {"LibreOffice recalc": rc_txt, "Engine compare": eng_txt, "Inputs fingerprint (SHA-256)": fp}
    for r in range(4, 16):
        if vl.cell(r, 1).value in stamp: vl.cell(r, 2).value = stamp[vl.cell(r, 1).value]
    wb.save(a.xlsx)
    libreoffice_recalc(a.xlsx, a.recalc_script)
    n_pass, n_warn, n_error, warns = tally_checks(a.xlsx)
    chk_txt = f"{n_pass} PASS / {n_warn} WARN / {n_error} ERROR"
    verdict = "READY" if (ok_rc and n_bad == 0 and n_error == 0) else "NOT READY"
    ts = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
    wb = load_workbook(a.xlsx); vl = wb["Version_Log"]
    stamp.update({"Checks": chk_txt, "Verdict": verdict, "Validated at (UTC)": ts})
    for r in range(4, 16):
        if vl.cell(r, 1).value in stamp: vl.cell(r, 2).value = stamp[vl.cell(r, 1).value]
    wb.save(a.xlsx)
    libreoffice_recalc(a.xlsx, a.recalc_script)

    with open(a.log, "w", encoding="utf-8") as f:
        f.write(f"# Mining Capacity Standard v{cc.VERSION} — validation log\n\n")
        f.write(f"- Workbook: `{os.path.basename(a.xlsx)}`\n- Data cut: {cc.DATA_CUT} · release {cc.RELEASE}\n- Inputs fingerprint (SHA-256): `{fp}`\n")
        f.write(f"- LibreOffice recalc: {rc_txt}\n- Engine compare: {eng_txt}\n- Checks: {chk_txt}\n- Verdict: **{verdict}**\n- Validated at: {ts}\n\n")
        if bad:
            f.write("## Mismatches\n" + "\n".join(f"- {b}" for b in bad) + "\n\n")
        f.write("## WARN items (release note)\n" + "\n".join(f"- {n} — {s}" for n, s in warns) + "\n")
    print(rc_txt); print(eng_txt); print(chk_txt); print("Verdict:", verdict); print("log:", a.log)
    sys.exit(0 if verdict == "READY" else 1)

if __name__ == "__main__":
    main()
