#!/usr/bin/env python3
"""Standalone verifier for the E110 interim bundle. Imports no CAIN code; standard library only.
    python3 verify_e110_offline.py .
Checks: SHA256SUMS for every file; governance pass/fail/blocked counts recomputed from the raw case rows;
the gate matrix uses only the allowed status words and its counts match; no gate claims PASS.
"""
import hashlib, json, sys
from pathlib import Path
d = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
ok, out = True, []
def check(name, cond, detail=""):
    global ok
    ok = ok and bool(cond); out.append(("PASS" if cond else "FAIL") + " " + name + (" " + detail if detail else ""))
for line in (d / "SHA256SUMS").read_text().splitlines():
    h, f = line.split("  ", 1)
    p = d / f
    check("sha256 " + f, p.exists() and hashlib.sha256(p.read_bytes()).hexdigest() == h)
g = json.loads((d / "GOVERNANCE_RESULTS.json").read_text())
for kind in ("baseline", "hardened"):
    rows = g[kind]["cases"]
    rec = (sum(1 for r in rows if r["pass"] is True), sum(1 for r in rows if r["pass"] is False), sum(1 for r in rows if r["pass"] is None))
    check(kind + " counts recomputed", rec == (g[kind]["passed"], g[kind]["failed"], g[kind]["blocked"]), str(rec))
    check(kind + " rows consistent", all(r["pass"] is None or r["pass"] == (r["executed"] == r["expected_executed"]) for r in rows))
check("hardened has no failing case", g["hardened"]["failed"] == 0)
race = next(r for r in g["hardened"]["cases"] if r["case"].startswith("KILL race"))
check("kill race fenced", race["executed"] is False and "effects_after_kill_in_resource_ledger=0" in race["reason"])
m = json.loads((d / "GATE_MATRIX.json").read_text())
allowed = {"PASS", "PARTIAL", "FAIL", "BLOCKED", "NOT TESTED", "RUNNING"}
check("gate statuses allowed", all(x["status"] in allowed for x in m["gates"]))
counts = {}
for x in m["gates"]:
    counts[x["status"]] = counts.get(x["status"], 0) + 1
check("gate counts match", counts == m["counts"], str(counts))
check("interim claims no PASS gate", counts.get("PASS", 0) == 0)
print("\n".join(out)); print("RESULT", "VALID" if ok else "INVALID", f"({sum(1 for o in out if o.startswith('PASS'))}/{len(out)} checks)")
sys.exit(0 if ok else 1)
