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

Recomputes every headline number from the raw run rows: certificates, audit-arm outcomes,
cell summaries, the hypotheses and the verdict. Checks the SHA-256 claim chain, the
preregistration hash, the salt commitments, the pinned E306 dependency hashes, 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 or the auditors.
"""
import hashlib
import json
import sys
from pathlib import Path

S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
ENG = ("auditor.py", "run.py")
DEPS = 5
GRAMMARS = ("A", "B")
P1 = ("honest3", "two_decoy3")
ARMS = ("PIN", "TRUTH", "P2_HONEST", "P2_ONE", "P2_SHARED", "P2_INDEP", "QUORUM3", "P2_TARGETED")
EX = {"E310_MANIFEST.json", "E310_SIGNED_BODY.json", "E310_VERIFICATION_RESULTS.json",
      "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json", "E310_OMEGA_SEAL.json",
      "E310_TAMPER_RESULTS.json", "E310_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,
        "failed": sum(1 for r in rows if r["failed"]),
        "correct": sum(1 for r in rows if r["correct"]),
        "mean_cert": sum((r["cert_size"] 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 / "E310_MANIFEST.json").read_text())
    ck("schema", man.get("schema") == "cain42.e310.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 / "E310_PREREGISTRATION.json").read_text())
    frz = json.loads((B / "E310_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((B / "E310_RUN_REPORT.json").read_text())
    rev = json.loads((B / "E310_SALT_REVEALED.json").read_text())
    ck("prereg hash", sha((B / "E310_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 / "E310_EXTERNAL_REVIEW_STATUS.json").read_text()).get("status") == "NOT_OBTAINED")
    ck("pinned dependency", len(pre.get("dependency_sha256", {})) == DEPS and
       all(len(h) == 64 for h in pre["dependency_sha256"].values()))
    ck("engine hashes", len(pre.get("engine_sha256", {})) == len(ENG))

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

    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["p1"], r["world"]))
        if not r["accepted"]:
            continue
        if r["cert_size"] != len(r["cert_rows"]):
            bad.append(("cert_size", r["grammar"], r["p1"], 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["p1"], 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["p1"], r["world"]))
        for a in ARMS:
            want = 0 if a == "PIN" else (3 * r["cert_size"] if a == "QUORUM3" else r["cert_size"])
            if r["arms"][a]["checks"] != want:
                bad.append(("arm_checks", a, r["grammar"], r["p1"], r["world"]))
    ck("row consistency", not bad, bad[:5])

    acc = [r for r in allr if r["accepted"]]
    cap = [r for r in acc if not r["correct"]]
    hon = [r for r in acc if r["correct"]]

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

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

    h1 = fa(allr, "TRUTH") == 0
    h2 = fa(allr, "P2_HONEST") == 0 and fa(allr, "P2_ONE") == 0
    h3 = (len(cap) > 0 and fa(cap, "P2_SHARED") >= 0.9 * len(cap))
    h4 = fa(allr, "QUORUM3") == 0 and (sum(1 for r in hon if r["arms"]["QUORUM3"]["accept"])
                                        >= 0.95 * len(hon))
    h5 = fa(allr, "P2_TARGETED") == 0 and refuses(allr, "P2_TARGETED") >= 0.9 * len(acc)
    rp = [r for r in rep["sets"]["replication"]["rows"] if r["accepted"]]
    h7 = (fa(rp, "TRUTH") == 0 and fa(rp, "P2_ONE") == 0 and fa(rp, "QUORUM3") == 0)
    exp = {"H1_truthful_audit_sound": h1, "H2_independent_audit_sound": h2,
           "H3_correlated_auditor_forges": h3, "H4_quorum_restores_soundness": h4,
           "H5_targeted_auditor_denies_not_forges": h5, "H7_replication": h7}
    H = rep["hypotheses"]
    for k, ok in exp.items():
        ck(f"{k} verdict", H[k]["verdict"] == ("SUPPORTED" if ok else "NOT_SUPPORTED"))
    ck("H1 count", H["H1_truthful_audit_sound"]["false_accepts"] == fa(allr, "TRUTH") and
       H["H1_truthful_audit_sound"]["certificates"] == len(acc))
    ck("H2 counts", H["H2_independent_audit_sound"]["p2_honest_false_accepts"] ==
       fa(allr, "P2_HONEST") and
       H["H2_independent_audit_sound"]["p2_one_false_accepts"] == fa(allr, "P2_ONE"))
    ck("H3 counts", H["H3_correlated_auditor_forges"]["captured_certificates"] == len(cap) and
       H["H3_correlated_auditor_forges"]["p2_shared_false_accepts"] == fa(cap, "P2_SHARED"))
    ck("H4 counts", H["H4_quorum_restores_soundness"]["false_accepts"] == fa(allr, "QUORUM3") and
       H["H4_quorum_restores_soundness"]["honest_accepts"] ==
       sum(1 for r in hon if r["arms"]["QUORUM3"]["accept"]))
    ck("H5 counts", H["H5_targeted_auditor_denies_not_forges"]["false_accepts"] ==
       fa(allr, "P2_TARGETED") and
       H["H5_targeted_auditor_denies_not_forges"]["refusals"] == refuses(allr, "P2_TARGETED"))
    verdict = ("FALLIBLE_AUDITOR_SUPPORTED" if all(exp.values()) else "NOT_SUPPORTED")
    ck("verdict", verdict == rep["verdict"] == man.get("label"))
    f = rep["finding"]
    ck("finding consistent", f["captured_certificates"] == len(cap) and
       f["p2_shared_forgeries"] == fa(cap, "P2_SHARED") and
       f["quorum_false_accepts"] == fa(allr, "QUORUM3") and
       f["targeted_false_accepts"] == fa(allr, "P2_TARGETED"))
    ck("quorum sound", fa(allr, "QUORUM3") == 0)
    ck("targeted forges none", fa(allr, "P2_TARGETED") == 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") == 48 and
       man.get("headline", {}).get("claims") == 384)

    ch = chain(allr)
    cp = json.loads((B / "checkpoints/claim_chain.json").read_text())
    ck("chain count", cp["count"] == 48)
    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 / "E310_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.e310.verify.v1", "checks": len(c),
                      "passed": passed, "failed": [x for x in c if not x["ok"]],
                      "verdict": verdict, "quorum_false_accepts": fa(allr, "QUORUM3"),
                      "shared_forgeries": fa(cap, "P2_SHARED"), "certificates": len(acc)},
                     ensure_ascii=False))
    return 0 if passed == len(c) else 1


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