#!/usr/bin/env python3
"""E236 standalone offline verifier (Track A/C/H/I, session e0).

Imports no CAIN code: Python stdlib + `cryptography` (Ed25519) only.
Usage:  python3 -I verify_e236_offline.py <bundle_dir>

Checks
  * preregistration PART1/PART2 hashes match their freeze records
  * revealed salts match the SHA-256 commitments frozen in PART2
  * every sealed task's outputs and 200 probe outputs are recomputed from its
    program with an independent re-implementation of the 12 primitives, and
    its uid is recomputed
  * the two stage receipts verify (Ed25519) and bind SHA-256 of the raw result
  * the knowledge-store journals are intact hash chains with the stated head
  * every preregistered verdict is recomputed from the raw per-stage solved sets
  * the governance campaign record: every case passed, KILL race 0 effects after fence
  * the manifest lists every file with its SHA-256, and no unlisted file exists
Not checked: that the solved task sets are reproducible by re-running the
search (the engine source is withheld; solution sequences were not recorded).
"""
import hashlib, json, math, sys
from pathlib import Path

D = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(".")
R = []


def check(name, ok, detail=""):
    R.append({"check": name, "ok": bool(ok), "detail": str(detail)[:300]})


def sha(b): return hashlib.sha256(b).hexdigest()
def jl(n): return json.loads((D / n).read_text())
def canon(o): return json.dumps(o, sort_keys=True, separators=(",", ":")).encode()


# ---------------- independent primitives (string transforms) ----------------
def _rot(s, k):
    o = []
    for ch in s:
        if "a" <= ch <= "z": o.append(chr((ord(ch) - 97 + k) % 26 + 97))
        elif "A" <= ch <= "Z": o.append(chr((ord(ch) - 65 + k) % 26 + 65))
        else: o.append(ch)
    return "".join(o)


P = {"upper": str.upper, "lower": str.lower, "rev": lambda s: s[::-1], "sort": lambda s: "".join(sorted(s)),
     "dedup": lambda s: "".join(dict.fromkeys(s)), "swap": str.swapcase, "take2": lambda s: s[:2],
     "drop2": lambda s: s[2:], "rep2": lambda s: s + s, "rot1": lambda s: _rot(s, 1),
     "rot2": lambda s: _rot(s, 2), "rot3": lambda s: _rot(s, 3)}


def run(seq, s):
    for n in seq: s = P[n](s)
    return s


# ---------------- analysis (identical to retention_analyze.py) --------------
ORDER = ("A", "B", "C", "D", "E", "F")


def mc(a, b):
    A, B = set(a), set(b); x = len(A - B); y = len(B - A); n = x + y
    return {"child_only": x, "parent_only": y, "n": n, "p_one_sided": sum(math.comb(n, k) for k in range(x, n + 1)) / 2 ** n if n else 1.0}


def holm(d):
    order = sorted(d.items(), key=lambda kv: kv[1]); out = {}; prev = 0.0
    for i, (k, p) in enumerate(order):
        prev = max(prev, min(1.0, (len(order) - i) * p)); out[k] = prev
    return out


def pooled(a, fams=ORDER): return [f + ":" + u for f in fams for u in a[f]]


def aset(r):
    st = r["stages"]; last = st[-1]["arms"]; early = ORDER[:-1]
    cons = pooled(last["consolidated"])
    c = {"A1": mc(cons, pooled(r["static"]["frozen"])), "A3": mc(pooled(last["consolidated"], early), pooled(last["replace"], early)),
         "A4": mc(cons, pooled(last["naive"])), "A5": mc(cons, pooled(r["static"]["compute2x"]))}
    hp = holm({k: v["p_one_sided"] for k, v in c.items()})
    sig = {k: c[k]["child_only"] > c[k]["parent_only"] and hp[k] < 0.05 for k in c}
    at = {f: set(st[k]["arms"]["consolidated"][f]) for k, f in enumerate(ORDER)}
    n = sum(len(at[f]) for f in early); fg = sum(len(at[f] - set(last["consolidated"][f])) for f in early)
    pz = mc(cons, pooled(last["poisoned"]))
    return sig, {"n": n, "forgotten": fg, "holds": n > 0 and fg <= 0.05 * n}, pz["child_only"] - pz["parent_only"] <= 3


try:
    for part in ("PART1", "PART2"):
        fr = jl(f"E236_PREREGISTRATION_{part}_FREEZE.json")
        check(f"{part} preregistration hash matches freeze", sha((D / f"E236_PREREGISTRATION_{part}.json").read_bytes()) == fr["preregistration_sha256"])
    pre = jl("E236_PREREGISTRATION_PART2.json")["parts"]["retention"]["content"]
    sr = jl("retention/E236_RETENTION_SALTS_REVEALED.json")
    com = pre["salt_commitments_sha256"]
    check("revealed salts match frozen commitments", all(sha(bytes.fromhex(v)) == com[s][f] for s in sr["salts"] for f, v in sr["salts"][s].items()))
    check("salt master commitment", sha(json.dumps(com, sort_keys=True).encode()) == pre["salt_master_commitment_sha256"])
    rep = jl("retention/E236_RETENTION_RUN_REPORT.json")
    check("report binds PART2 hash", rep["preregistration_sha256"] == jl("E236_PREREGISTRATION_PART2_FREEZE.json")["preregistration_sha256"])
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
    pub = Ed25519PublicKey.from_public_bytes(bytes.fromhex(jl("retention/E236_AUTHORITY_PUBKEY.json")["ed25519_public_key_hex"]))
    raw = {}
    for s in ("main", "replication"):
        rb = (D / f"retention/E236_RETENTION_{s.upper()}.json").read_bytes(); raw[s] = json.loads(rb)
        rc = dict(rep["stages"][s]["receipt"]); sig = rc.pop("signature")
        try:
            pub.verify(bytes.fromhex(sig), canon(rc)); ok = True
        except Exception:
            ok = False
        check(f"{s}: stage receipt signature (Ed25519)", ok)
        check(f"{s}: receipt binds SHA-256 of the raw result", rc["result_sha256"] == sha(canon(raw[s])))
        check(f"{s}: MCPGate decision ALLOW before execution", rep["stages"][s]["gate"]["decision"] == "ALLOW")
        bad = 0; uids = 0
        for f, ts in raw[s]["sealed"].items():
            for t in ts:
                prog = tuple(t["program"])
                if [run(prog, x) for x in t["inputs"]] != t["outputs"] or [run(prog, x) for x in t["probe_inputs"]] != t["probe_outputs"]:
                    bad += 1
                if sha(json.dumps([t["fam"], t["k"], list(prog), t["inputs"], t["outputs"]], sort_keys=True).encode())[:16] != t["uid"]:
                    uids += 1
        n = sum(len(ts) for ts in raw[s]["sealed"].values())
        check(f"{s}: {n} sealed tasks recomputed from programs (outputs + 200 probes)", bad == 0 and n == 288, f"bad={bad}")
        check(f"{s}: sealed task uids recomputed", uids == 0, f"mismatch={uids}")
        check(f"{s}: every probe set has 200 unseen inputs", all(len(t["probe_inputs"]) == 200 for ts in raw[s]["sealed"].values() for t in ts))
        st = raw[s]["store"]; head = "0" * 64; okc = True
        for ev in st["journal"]:
            e = {k: v for k, v in ev.items() if k != "h"}
            head = sha(json.dumps({"prev": head, **e}, sort_keys=True).encode())
            okc &= head == ev["h"]
        check(f"{s}: knowledge-store journal hash chain intact", okc and head == st["head"])
        check(f"{s}: restart reload identical (fresh process)", rep["restart"][s]["identical"])
    A = jl("retention/E236_RETENTION_ANALYSIS.json")
    sm, a2m, a6m = aset(raw["main"]); sr_, a2r, _ = aset(raw["replication"])
    rec = {"H-A1": sm["A1"], "H-A2": a2m["holds"], "H-A3": sm["A3"], "H-A4": sm["A4"], "H-A5": sm["A5"], "H-A6": a6m,
           "H-A7": all(rep["restart"][s]["identical"] for s in ("main", "replication")),
           "H-A8": a2r["holds"] and sr_["A3"] and sr_["A4"]}
    for k, v in rec.items():
        check(f"{k} recomputed from raw rows = published ({v})", A["H"][k]["holds"] == v)
    ver = "CONTINUAL_RETENTION_SUPPORTED" if all(rec[k] for k in ("H-A1", "H-A2", "H-A3", "H-A7", "H-A8")) else "CONTINUAL_RETENTION_NOT_SUPPORTED"
    check(f"verdict recomputed = published ({ver})", A["verdict"] == ver)
    g = rep["governance"]
    check(f"governance: {g['passed']}/{g['total']} adversarial/control cases as expected", g["passed"] == g["total"] and all(t["pass"] for t in g["tests"]))
    kr = g["kill_race"]
    check(f"cross-process KILL race: fence at {kr['fence_seq']}, 0 effects after", kr["fence_seq"] > 0 and kr["effects_after_fence"] == 0)
    check("H-I1 recomputed", A["H"]["H-I1"]["holds"] == (g["passed"] == g["total"] and kr["pass"]))
    m = jl("E236_MANIFEST.json")
    listed = {e["path"]: e["sha256"] for e in m["files"]}
    check("manifest file hashes", all(sha((D / p).read_bytes()) == h for p, h in listed.items()))
    actual = {str(p.relative_to(D)) for p in D.rglob("*") if p.is_file()} - {"E236_MANIFEST.json"}
    check("no unlisted file in the bundle", actual == set(listed), sorted(actual ^ set(listed))[:5])
except Exception as ex:  # any missing file or malformed record is a failure
    check("bundle readable", False, repr(ex))

ok = all(r["ok"] for r in R)
for r in R:
    print(("PASS " if r["ok"] else "FAIL ") + r["check"] + ("" if r["ok"] else f"  [{r['detail']}]"))
print(json.dumps({"checks": len(R), "passed": sum(r["ok"] for r in R), "ok": ok}))
sys.exit(0 if ok else 1)
