#!/usr/bin/env python3
"""Standalone verifier for E238 c8 (model transfer). Imports no CAIN code; reimplements the 12 primitives.
Usage: python3 -I c8_verify.py <dir with E238_PREREGISTRATION_PART1.json, E238_C8_MODEL_TRANSFER_MAIN.json[, _REP.json],
       E238_C8_*_SUBMISSION.json, E238_C8_SALTS_REVEALED.json>
Re-executes every model answer on the shown examples and the 200 hidden probes, recomputes every arm's solved set,
the McNemar contrasts, Holm and verdicts, and checks the salt reveal and the MCPGate receipt for each submission."""
import hashlib, json, sys
from math import comb
from pathlib import Path
def _rot(s, k): return "".join(chr((ord(c) - 97 + k) % 26 + 97) if "a" <= c <= "z" else chr((ord(c) - 65 + k) % 26 + 65) if "A" <= c <= "Z" else c for c in s)
PR = {"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 = PR[n](s)
    return s
def sha(b): return hashlib.sha256(b).hexdigest()
def canon(o): return json.dumps(o, sort_keys=True, separators=(",", ":")).encode()
def mc(A, B):
    x, y = len(A - B), len(B - A); n = x + y
    return {"child_only": x, "parent_only": y, "n": n, "p_one_sided": sum(comb(n, k) for k in range(x, n + 1)) / (2 ** n) if n else 1.0}
def holm(ps):
    o = sorted(ps, key=lambda k: ps[k]); m = len(o); out = {}; r = 0.0
    for i, k in enumerate(o): r = max(r, min(1.0, ps[k] * (m - i))); out[k] = r
    return out
def main():
    B = Path(sys.argv[1] if len(sys.argv) > 1 else "."); C = []
    def ck(n, ok, d=""): C.append({"check": n, "ok": bool(ok), "detail": str(d)[:200]})
    pre_t = (B / "E238_PREREGISTRATION_PART1.json").read_text(); pre_sha = sha(pre_t.encode())
    salts = json.loads((B / "E238_C8_SALTS_REVEALED.json").read_text())
    for k, v in salts["salts"].items(): ck(f"salt {k} matches frozen commitment", sha(bytes.fromhex(v)) in pre_t)
    for which in ("MAIN", "REP"):
        p = B / f"E238_C8_MODEL_TRANSFER_{which}.json"
        if not p.exists(): continue
        d = json.loads(p.read_text()); sub = json.loads((B / f"E238_C8_SEALED_{which}_SUBMISSION.json").read_text())
        ck(f"{which} preregistration hash", d["preregistration_sha256"] == pre_sha)
        T = {(t["fam"], t["uid"]): t for t in d["task_manifest"]}
        ck(f"{which} probes 200 per task, programs reproduce outputs", all(len(t["probe_inputs"]) == 200 and all(run(t["program"], x) == y for x, y in zip(t["probe_inputs"], t["probe_outputs"])) and all(run(t["program"], x) == y for x, y in zip(t["inputs"], t["outputs"])) for t in T.values()))
        helpers = {(r["fam"], r["uid"], r["arm"]): r["helpers"] for r in sub["rows"]}
        solved = {}; bad = 0
        for r in d["results"]:
            t = T[(r["fam"], r["uid"])]; hp = helpers[(r["fam"], r["uid"], r["arm"])]; ok = False
            prog = r.get("program") or []
            seq = []
            for n in prog:
                if n in hp: seq += hp[n]
                elif n in PR: seq.append(n)
                else: seq = None; break
            if seq:
                ok = all(run(seq, x) == y for x, y in zip(t["inputs"], t["outputs"])) and all(run(seq, x) == y for x, y in zip(t["probe_inputs"], t["probe_outputs"]))
            if ok != r["solved"]: bad += 1
            if ok: solved.setdefault(r["arm"], set()).add((r["fam"], r["uid"]))
        ck(f"{which} every answer re-executed; solved flags agree", bad == 0, bad)
        a = d["analysis"]; ck(f"{which} solved counts recomputed", all(a["solved"].get(k, 0) == len(v) for k, v in solved.items()), (a["solved"], {k: len(v) for k, v in solved.items()}))
        ck(f"{which} submission covers every result", len(sub["rows"]) == len(d["results"]))
        try:
            from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
            rc = sub["receipt"]; Ed25519PublicKey.from_public_bytes(bytes.fromhex(sub["permit_public_key"])).verify(bytes.fromhex(rc["signature"]), canon({k: v for k, v in rc.items() if k != "signature"}))
            ck(f"{which} MCPGate receipt signature", rc["decision"] == "EXECUTED" and sub["gate"]["decision"] == "ALLOW")
        except Exception as ex: ck(f"{which} MCPGate receipt signature", False, ex)
        ck(f"{which} receipt binds the batch id", sub["receipt"]["result_sha256"] == sha(canon(sub["batch_id"])))
        if which == "MAIN":
            new = {t for t in T if t[0] in ("G", "H", "I")}; S = lambda k: solved.get(k, set())
            K = {"H-M1": mc(S("model_cain"), S("model_alone")), "H-M2": mc(S("model_cain"), S("model_random")), "H-M3": mc(S("model_cain") & new, S("model_alone") & new)}
            hp_ = holm({k: v["p_one_sided"] for k, v in K.items()})
            for k, v in K.items():
                ck(f"{k} recomputed", a["hypotheses"][k]["contrast"] == v and abs(a["hypotheses"][k]["holm_p"] - hp_[k]) < 1e-12 and a["hypotheses"][k]["verdict"] == ("SUPPORTED" if v["child_only"] > v["parent_only"] and hp_[k] < 0.05 else "NOT_SUPPORTED"), (a["hypotheses"][k], v))
    ok = all(c["ok"] for c in C)
    print(json.dumps({"checks": len(C), "passed": sum(c["ok"] for c in C), "ok": ok, "verification": "E238 c8 model transfer (answers re-executed)"}))
    for c in C:
        if not c["ok"]: print("FAIL", c["check"], c["detail"])
    return 0 if ok else 1
if __name__ == "__main__": sys.exit(main())
