"""Validate + stamp the Mining Cost Standard workbook.
Steps: (1) LibreOffice recalc & formula-error scan; (2) independent engine compare; (3) Checks sheet scan (ERROR blocks);
(4) blind-verification confidence summary; (5) fingerprint; (6) stamp Version_Log; (7) recalc again and re-verify stamped file.
Usage: validate_cost_model.py <xlsx> [--recalc]"""
import json, sys, os, subprocess, hashlib, datetime, shutil
# Working folder: COST_DIR, else the folder of this script (reproducibility fix 2026-11-15: a hard-coded build path was replaced; logic unchanged)
SP=os.environ.get("COST_DIR") or os.path.dirname(os.path.abspath(__file__))
NORM=f"{SP}/normalized.json" if os.path.exists(f"{SP}/normalized.json") else sorted(__import__("glob").glob(f"{SP}/mining_cost_v1.0_inputs_*.json"))[-1]  # the published inputs file is normalized.json, byte-identical
RECALC=os.environ.get("RECALC") or "/mnt/skills/public/xlsx/scripts/recalc.py"  # LibreOffice recalculation helper; without it run soffice --headless --convert-to xlsx first
xlsx=sys.argv[1]; do_recalc="--recalc" in sys.argv
from openpyxl import load_workbook
meta=json.load(open(f"{SP}/build_meta.json"))
log=[]
def run(cmd):
    r=subprocess.run(cmd,capture_output=True,text=True); return r.returncode, r.stdout.strip(), r.stderr.strip()

# 1 recalc
rc_status="skipped"
if do_recalc:
    code,out,err=run(["python3",RECALC,xlsx,"240"])
    try: j=json.loads(out[out.index("{"):]); rc_status=f"{j['status']} — {j['total_formulas']} formulas, {j['total_errors']} errors"
    except Exception: rc_status=f"recalc failed: {out[-200:]} {err[-200:]}"
log.append(("LibreOffice recalc",rc_status))
# 2 engine
code,out,err=run(["python3","-I",os.path.join(os.path.dirname(os.path.abspath(__file__)),"mining_cost_engine.py"),"--xlsx",xlsx,"--json",f"{SP}/engine_result.json"])
first=out.splitlines()[0] if out else err[-200:]
eng_status=first.replace("Engine compare: ","")+(" — OK" if code==0 else " — MISMATCHES")
log.append(("Engine compare",eng_status))
# 3 checks
wb=load_workbook(xlsx,data_only=True); ws=wb["Checks"]
cnt={"PASS":0,"WARN":0,"ERROR":0}
for r in range(4,ws.max_row+1):
    hv=ws[f"H{r}"].value
    if hv in cnt and ws[f"A{r}"].value and not str(ws[f"A{r}"].value).startswith(("PASS","WARN","ERROR","Verdict","Summary")): cnt[hv]+=1
chk_status=f"{cnt['PASS']} PASS / {cnt['WARN']} WARN / {cnt['ERROR']} ERROR"
log.append(("Checks",chk_status))
# 4 blind verification summary from Data sheet
wsd=wb["Data"]; conf={}
for r in range(4,wsd.max_row+1):
    c=wsd[f"H{r}"].value
    if c: conf[c]=conf.get(c,0)+1
ver_status=", ".join(f"{k}: {v}" for k,v in sorted(conf.items())) if conf else "not run"
log.append(("Blind verification",ver_status))
# 5 fingerprint
sha=hashlib.sha256(open(NORM,"rb").read()).hexdigest()
verdict="READY" if (cnt["ERROR"]==0 and code==0 and ("success" in rc_status or not do_recalc)) else "BLOCKED"
stamp=datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
log.append(("Verdict",verdict)); log.append(("Validated at (UTC)",stamp))
# 6 stamp Version_Log (formulas preserved: load without data_only)
wbf=load_workbook(xlsx); wv=wbf["Version_Log"]; rows=meta["vl_rows"]
for k,val in log:
    if k in rows: wv[f"B{rows[k]}"].value=val
wv[f"B{rows['Inputs fingerprint (SHA-256 normalized.json)']}"].value=sha
wbf.save(xlsx)
# 7 recalc again so Public_Summary integrity cells show stamped values
if do_recalc:
    code2,out2,err2=run(["python3",RECALC,xlsx,"240"])
    try: j2=json.loads(out2[out2.index("{"):]); rc2=f"{j2['status']} ({j2['total_errors']} errors)"
    except Exception: rc2="recalc2 failed"
else: rc2="skipped"
# write log
md=[f"# Mining Cost Standard — validation log ({stamp})","",f"Workbook: `{os.path.basename(xlsx)}`",f"Inputs fingerprint (SHA-256 normalized.json): `{sha}`",""]
for k,val in log: md.append(f"- **{k}**: {val}")
md.append(f"- **Post-stamp recalc**: {rc2}")
# warn/error details
md.append(""); md.append("## Checks — non-PASS rows")
for r in range(4,ws.max_row+1):
    hv=ws[f"H{r}"].value
    if hv in ("WARN","ERROR"): md.append(f"- {hv}: {ws[f'A{r}'].value} — {ws[f'B{r}'].value} {ws[f'C{r}'].value}: derived {ws[f'D{r}'].value} vs {ws[f'E{r}'].value} (Δ {ws[f'F{r}'].value}). {ws[f'J{r}'].value}")
open(f"{SP}/validation_log.md","w").write("\n".join(md))
print("\n".join(f"{k}: {v}" for k,v in log)); print("Post-stamp recalc:",rc2); print("Verdict",verdict)
sys.exit(0 if verdict=="READY" else 1)
