#!/usr/bin/env python3
"""E137 offline integrity verifier. Imports no CAIN code; unsigned bundle."""
import hashlib, json, pathlib, sys
R = pathlib.Path(__file__).resolve().parent
ok = 0; bad = 0
def ck(name, cond, detail=""):
    global ok, bad
    if cond: ok += 1; print("PASS", name, detail)
    else: bad += 1; print("FAIL", name, detail)
m = json.loads((R/"MANIFEST.json").read_text())
ck("schema", m.get("schema") == "cain.e137.bundle.manifest.v1")
ck("agi_honest", m.get("agi_status") == "NOT ESTABLISHED")
ck("rsi_honest", m.get("rsi_status") == "EXPERIMENTAL")
ck("unsigned_label", m.get("integrity") == "UNSIGNED_SHA256")
for f in m["files"]:
    p = R/f["path"]
    ck("sha256:"+f["path"], p.exists() and hashlib.sha256(p.read_bytes()).hexdigest() == f["sha256"])
r = json.loads((R/"RESULTS.json").read_text())
d = json.loads((R/"DAG.json").read_text())
ck("candidate_count", len(r["candidates"]) == 10, str(len(r["candidates"])))
ck("dag_edges", len(d["edges"]) == 9, str(len(d["edges"])))
ids = {c["candidate_id"] for c in r["candidates"]}
ck("parents_exist", all(c["parent_id"] is None or c["parent_id"] in ids for c in r["candidates"]))
ck("g0_frozen", next(c for c in r["candidates"] if c["candidate_id"]=="G0")["sealed_solved"] == 11)
ck("best_g2", r["best_g2"] == "G2-C1" and r["best_solved"] == 29)
ck("control", r["control_solved"] == 23)
ck("tier8", r["tier8_best"] == 5 and r["tier8_control"] == 3)
ck("tier16_blocked", "BLOCKED" in r["tier16"]["status"])
ck("tier12_zero", r["tier12"]["best"] == 0)
ck("seeded_30", all(c["sealed_tasks"] == 30 for c in r["candidates"]))
ck("no_model", all("model" not in c["strategy"] for c in r["candidates"]))
print(f"\n{ok} checks passed; {bad} failed")
sys.exit(0 if bad == 0 else 1)
