#!/usr/bin/env python3
"""E306 standalone offline verifier (stdlib + cryptography; imports no CAIN code).

Recomputes every headline number from the raw run rows: certificate sizes and validity,
lie overlap, the theorem check, all five arm outcomes, cell summaries, the hypotheses and
the verdict. Checks the SHA-256 claim chain, the preregistration hash, the salt
commitments, the manifest signature, every file digest and the Merkle root. The engine
source is withheld, so the verifier is record-level: it does not re-execute the learner.
"""
import hashlib
import json
import sys
from pathlib import Path

S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
ENG = ("world.py", "grammar.py", "oracles.py", "learner.py", "certificate.py", "run.py")
GRAMMARS = ("A", "B")
PANELS = ("honest3", "one_decoy3", "two_decoy3", "two_far_decoy3", "two_random3")
ARMS = ("PIN", "RAND_MATCH", "CERT_HALF", "ALL", "CERT_FULL")
EX = {"E306_MANIFEST.json", "E306_SIGNED_BODY.json", "E306_VERIFICATION_RESULTS.json",
      "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json", "E306_OMEGA_SEAL.json",
      "E306_TAMPER_RESULTS.json", "E306_ACCEPTANCE_REGISTRY.json"}


def canon(o):
    return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()


def sha(b):
    return hashlib.sha256(b).hexdigest()


def merkle(paths):
    leaves = sorted(sha(p.read_bytes()) for p in paths)
    if not leaves:
        return sha(b"")
    while len(leaves) > 1:
        if len(leaves) % 2:
            leaves.append(leaves[-1])
        leaves = [sha((leaves[i] + leaves[i + 1]).encode())
                  for i in range(0, len(leaves), 2)]
    return leaves[0]


def chain(rows):
    prev = "0" * 64
    out = []
    for r in rows:
        h = sha((prev + sha(canon(r))).encode())
        out.append({"i": len(out), "prev": prev, "hash": h})
        prev = h
    return out


def summarise(rows):
    n = len(rows)
    ac = sum(1 for r in rows if r["accepted"])
    return {
        "n": n,
        "accepted": ac,
        "correct": sum(1 for r in rows if r["correct"]),
        "false_accept": sum(1 for r in rows if r["false_accept"]),
        "failed": sum(1 for r in rows if r["failed"]),
        "mean_labels": sum(r["labels"] for r in rows) / n,
        "mean_cert": sum((r["cert_size"] or 0) for r in rows if r["accepted"]) / max(1, ac),
        "mean_lie_overlap": sum((r["lie_overlap"] or 0) for r in rows if r["accepted"]) / max(1, ac),
        "arms": {a: {
            "accepts": sum(1 for r in rows if r["accepted"] and r["arms"][a]["accept"]),
            "false_accepts": sum(1 for r in rows if r["accepted"] and r["arms"][a]["false_accept"]),
            "false_refusals": sum(1 for r in rows if r["accepted"] and r["arms"][a]["false_refusal"]),
            "mean_checks": sum((r["arms"][a]["checks"] for r in rows if r["accepted"])) / max(1, ac),
        } for a in ARMS},
    }


def main():
    B = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
    c = []

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

    man = json.loads((B / "E306_MANIFEST.json").read_text())
    ck("schema", man.get("schema") == "cain42.e306.manifest.v1")
    ck("status", man.get("status") == S)
    body = {k: v for k, v in man.items() if k != "signature"}
    try:
        from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(
            bytes.fromhex(man["signature"]), canon(body))
        ck("signature", True)
    except Exception as ex:
        ck("signature", False, ex)
    files = man.get("files", {})
    ck("files present", all((B / k).exists() for k in files))
    ck("file hashes", not [k for k, h in files.items()
                           if (B / k).exists() and sha((B / k).read_bytes()) != h])
    ck("merkle", merkle(sorted(B / k for k in files if (B / k).exists())) == man.get("merkle_root"))
    present = {str(x.relative_to(B)) for x in B.rglob("*")
               if x.is_file() and "__pycache__" not in x.parts}
    ck("no unlisted file", not (present - set(files) - EX), sorted(present - set(files) - EX)[:5])
    ck("source withheld", not any((B / n).exists() for n in ENG))

    pre = json.loads((B / "E306_PREREGISTRATION.json").read_text())
    frz = json.loads((B / "E306_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((B / "E306_RUN_REPORT.json").read_text())
    rev = json.loads((B / "E306_SALT_REVEALED.json").read_text())
    dev = json.loads((B / "E306_DEVIATIONS.json").read_text())
    ck("prereg hash", sha((B / "E306_PREREGISTRATION.json").read_bytes()) ==
       frz["preregistration_sha256"])
    ck("freeze before run", frz["frozen_at"] <= rep["generated_at"])
    ck("two salts", set(rev["salts"]) == {"primary", "replication"})
    ck("salt commitments", all(sha(bytes.fromhex(rev["salts"][k])) ==
                               pre["salt_commitment_sha256"][k] for k in rev["salts"]))
    ck("external not faked",
       json.loads((B / "E306_EXTERNAL_REVIEW_STATUS.json").read_text()).get("status") == "NOT_OBTAINED")
    ck("deviation recorded", len(dev.get("deviations", [])) >= 1 and
       all(d.get("design_unchanged") for d in dev["deviations"]))
    ck("deviation hashes", all(
        d["post_engine_sha256"]["cain/cain2027/e306/run.py"] == pre["engine_sha256"]["cain/cain2027/e306/run.py"]
        for d in dev["deviations"] if "post_engine_sha256" in d))
    ck("engine hashes recorded", len(pre.get("engine_sha256", {})) == 6)

    allr = []
    for salt in ("primary", "replication"):
        st = rep["sets"][salt]
        rows = st["rows"]
        allr += rows
        ck(f"{salt} rows", len(rows) == 60, len(rows))
        ck(f"{salt} unique", len({(r["grammar"], r["panel"], r["world"]) for r in rows}) == 60)
        for g in GRAMMARS:
            for p in PANELS:
                k = f"{g}|{p}"
                ck(f"{salt} {k}", summarise([r for r in rows if r["grammar"] == g and
                                             r["panel"] == p]) == st["summary"][k])
    ck("total runs", len(allr) == 120, len(allr))

    # per-row structural consistency
    bad = []
    for r in allr:
        expect_correct = bool(r["accepted"] and r["claimed_mask"] == r["truth_mask"])
        if r["correct"] != expect_correct:
            bad.append(("correct", r["grammar"], r["panel"], r["world"]))
        if r["false_accept"] != bool(r["accepted"] and not expect_correct):
            bad.append(("false_accept", r["grammar"], r["panel"], r["world"]))
        if r["accepted"]:
            if r["cert_size"] != len(r["cert_rows"]):
                bad.append(("cert_size", r["grammar"], r["panel"], r["world"]))
            lie = sum(1 for a in r["cert_rows"] if (r["corrupt_mask"] >> a) & 1)
            if lie != r["lie_overlap"]:
                bad.append(("lie_overlap", r["grammar"], r["panel"], r["world"]))
            if r["arms"]["CERT_FULL"]["checks"] != r["cert_size"]:
                bad.append(("cf_checks", r["grammar"], r["panel"], r["world"]))
            if r["arms"]["ALL"]["checks"] != r["labels"]:
                bad.append(("all_checks", r["grammar"], r["panel"], r["world"]))
            if r["arms"]["RAND_MATCH"]["checks"] != min(r["cert_size"], r["labels"]):
                bad.append(("rm_checks", r["grammar"], r["panel"], r["world"]))
            if r["arms"]["CERT_HALF"]["checks"] != r["cert_size"] // 2:
                bad.append(("ch_checks", r["grammar"], r["panel"], r["world"]))
            if r["arms"]["PIN"]["checks"] != 0:
                bad.append(("pin_checks", r["grammar"], r["panel"], r["world"]))
            for a in ARMS:
                if r["arms"][a]["false_accept"] != bool(r["arms"][a]["accept"] and not expect_correct):
                    bad.append(("arm_fa", a, r["grammar"], r["panel"], r["world"]))
                if r["arms"][a]["false_refusal"] != bool((not r["arms"][a]["accept"]) and expect_correct):
                    bad.append(("arm_fr", a, r["grammar"], r["panel"], r["world"]))
    ck("row consistency", not bad, bad[:5])

    acc = [r for r in allr if r["accepted"]]
    honest = [r for r in allr if r["panel"] == "honest3"]
    lying = [r for r in allr if r["panel"] != "honest3"]
    wrong = [r for r in acc if not r["correct"]]

    def fa(rows, arm):
        return sum(1 for r in rows if r["accepted"] and r["arms"][arm]["false_accept"])

    def fr(rows, arm):
        return sum(1 for r in rows if r["accepted"] and r["arms"][arm]["false_refusal"])

    h1 = (all(r["cert_valid"] for r in honest if r["accepted"]) and
          fa(honest, "CERT_FULL") == 0 and fr(honest, "CERT_FULL") == 0 and
          len([r for r in honest if r["accepted"]]) == len(honest))
    mean_cert_h = sum(r["cert_size"] for r in honest if r["accepted"]) / max(1, len(honest))
    mean_labels_h = sum(r["labels"] for r in honest) / max(1, len(honest))
    h2 = mean_cert_h <= 0.65 * mean_labels_h and mean_cert_h <= 25
    h3 = all(r["lie_overlap"] >= 1 for r in wrong)
    h4 = (fa(allr, "CERT_FULL") == 0 and fa(allr, "RAND_MATCH") >= 1 and
          fa(allr, "RAND_MATCH") > fa(allr, "CERT_FULL"))
    h5 = fa(lying, "CERT_HALF") >= 1
    rand = [r for r in allr if r["panel"] == "two_random3"]
    h6 = fa(rand, "CERT_FULL") == 0 and fa(rand, "PIN") >= 1
    h7 = (fa(allr, "ALL") == fa(allr, "CERT_FULL") and
          sum(1 for r in acc if r["arms"]["ALL"]["accept"]) ==
          sum(1 for r in acc if r["arms"]["CERT_FULL"]["accept"]) and
          (sum(r["arms"]["ALL"]["checks"] for r in acc) >
           sum(r["arms"]["CERT_FULL"]["checks"] for r in acc)))
    rp = rep["sets"]["replication"]["rows"]
    h8 = (all(r["cert_valid"] for r in rp if r["panel"] == "honest3" and r["accepted"]) and
          fa(rp, "CERT_FULL") == 0 and fa([r for r in rp if r["panel"] == "two_random3"], "PIN") >= 1)
    exp = {"H1_honest_certificate_soundness": h1, "H2_verification_compression": h2,
           "H3_lie_touches_certificate": h3, "H4_certificate_safety_under_collusion": h4,
           "H5_partial_certificate_unsound": h5, "H6_incoherent_corruption": h6,
           "H7_all_rows_no_better": h7, "H8_replication": h8}
    H = rep["hypotheses"]
    for k, ok in exp.items():
        ck(f"{k} verdict", H[k]["verdict"] == ("SUPPORTED" if ok else "NOT_SUPPORTED"))
    ck("H1 counts", H["H1_honest_certificate_soundness"]["honest_accepted"] ==
       sum(1 for r in honest if r["accepted"]) and
       H["H1_honest_certificate_soundness"]["invalid_certs"] ==
       sum(1 for r in honest if r["accepted"] and not r["cert_valid"]))
    ck("H2 counts", abs(H["H2_verification_compression"]["mean_cert_honest"] - mean_cert_h) < 0.005 and
       abs(H["H2_verification_compression"]["mean_labels_honest"] - mean_labels_h) < 0.005)
    ck("H3 counts", H["H3_lie_touches_certificate"]["wrong_accepts"] == len(wrong) and
       H["H3_lie_touches_certificate"]["cert_touches_lie"] ==
       sum(1 for r in wrong if r["lie_overlap"] >= 1))
    ck("H4 counts", H["H4_certificate_safety_under_collusion"]["cert_full_false_accepts"] ==
       fa(allr, "CERT_FULL") and
       H["H4_certificate_safety_under_collusion"]["rand_match_false_accepts"] ==
       fa(allr, "RAND_MATCH") and
       H["H4_certificate_safety_under_collusion"]["pin_false_accepts"] == fa(allr, "PIN"))
    ck("H5 counts", H["H5_partial_certificate_unsound"]["cert_half_false_accepts_lying"] ==
       fa(lying, "CERT_HALF"))
    ck("H6 counts", H["H6_incoherent_corruption"]["pin_false_accepts"] == fa(rand, "PIN") and
       H["H6_incoherent_corruption"]["cert_full_false_accepts"] == fa(rand, "CERT_FULL"))
    ck("H7 counts", H["H7_all_rows_no_better"]["all_checks"] ==
       sum(r["arms"]["ALL"]["checks"] for r in acc) and
       H["H7_all_rows_no_better"]["cert_full_checks"] ==
       sum(r["arms"]["CERT_FULL"]["checks"] for r in acc))
    req = [k for k in exp]
    verdict = ("CERTIFICATE_IDENTIFICATION_SUPPORTED"
               if all(exp.values()) else "NOT_SUPPORTED")
    ck("verdict", verdict == rep["verdict"] == man.get("label"))

    th = rep["theorem"]
    ck("theorem", th["wrong_accepts_checked"] == len(wrong) and
       th["cert_intersects_corruption"] == sum(1 for r in wrong if r["lie_overlap"] >= 1) and
       th["cert_full_false_accepts"] == fa(allr, "CERT_FULL") and
       th["cert_full_false_accepts"] == 0)
    ck("certificate safety", fa(allr, "CERT_FULL") == 0 and fa(allr, "ALL") == 0)
    ck("certificates", len(acc) == rep["resources"]["certificates"] and len(acc) > 0)
    ck("manifest headline", man.get("headline", {}).get("verdict") == rep["verdict"] and
       man.get("headline", {}).get("runs") == 120 and
       man.get("headline", {}).get("claims") == 600)

    ch = chain(allr)
    cp = json.loads((B / "checkpoints/claim_chain.json").read_text())
    ck("chain count", cp["count"] == 120)
    ck("chain head", cp["head"] == ch[-1]["hash"])
    ck("chain mid", cp["mid"] == ch[len(ch) // 2]["hash"])
    ck("chain recompute", sha((ch[-2]["hash"] + sha(canon(allr[-1]))).encode()) == ch[-1]["hash"])
    ck("status line", S in (B / "E306_FINAL_REPORT.md").read_text())
    ck("limits present", len(rep.get("limits", [])) >= 5)
    ck("zero model calls", rep["resources"]["model_calls"] == 0)

    passed = sum(1 for x in c if x["ok"])
    print(json.dumps({"schema": "cain42.e306.verify.v1", "checks": len(c),
                      "passed": passed, "failed": [x for x in c if not x["ok"]],
                      "verdict": verdict, "cert_full_false_accepts": fa(allr, "CERT_FULL"),
                      "certificates": len(acc)}, ensure_ascii=False))
    return 0 if passed == len(c) else 1


if __name__ == "__main__":
    sys.exit(main())
