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

Recomputes every headline number from the raw run rows and the per-cell outcome bitmasks:
the single-auditor forgery curve, the honest-certificate liveness curve, every quorum cell,
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.
"""
import hashlib
import json
import sys
from pathlib import Path

S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
ENG = ("correlation.py", "run.py")
DEPS = 5
GRAMMARS = ("A", "B")
P1 = ("honest3", "two_decoy3")
RHOS = ("0", "0.25", "0.5", "0.75", "1")
QUORUMS = ("1,0,0", "1,1,0", "1,0.5,0.5", "0.5,0.5,0.5", "1,0.75,0.5", "0,0,0")
DRAWS = 50
EX = {"E311_MANIFEST.json", "E311_SIGNED_BODY.json", "E311_VERIFICATION_RESULTS.json",
      "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json", "E311_OMEGA_SEAL.json",
      "E311_TAMPER_RESULTS.json", "E311_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 frac(rows, kind, key):
    a = n = 0
    for r in rows:
        c = r[kind][key]
        a += c["accepts"]
        n += c["draws"]
    return a / max(1, n), a, n


def monotone(vals, tol=0.005):
    return all(vals[i] <= vals[i + 1] + tol for i in range(len(vals) - 1))


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 / "E311_MANIFEST.json").read_text())
    ck("schema", man.get("schema") == "cain42.e311.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 / "E311_PREREGISTRATION.json").read_text())
    frz = json.loads((B / "E311_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((B / "E311_RUN_REPORT.json").read_text())
    rev = json.loads((B / "E311_SALT_REVEALED.json").read_text())
    ck("prereg hash", sha((B / "E311_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 / "E311_EXTERNAL_REVIEW_STATUS.json").read_text()).get("status") == "NOT_OBTAINED")
    ck("pinned dependency", len(pre.get("dependency_sha256", {})) == DEPS)
    ck("engine hashes", len(pre.get("engine_sha256", {})) == len(ENG))

    allr = []
    for salt in ("primary", "replication"):
        rows = rep["sets"][salt]["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)
    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"]))
        if not (0 <= r["cert_in_D"] <= min(r["cert_size"], r["D_size"])):
            bad.append(("cert_in_D", r["grammar"], r["p1"], r["world"]))
        for kind, keys in (("single", RHOS), ("quorum", QUORUMS)):
            for key in keys:
                cell = r[kind][key]
                if cell["draws"] != DRAWS:
                    bad.append(("draws", kind, key))
                if int(cell["outcomes"], 16).bit_count() != cell["accepts"]:
                    bad.append(("bitmask", kind, key))
                if not (0 <= cell["accepts"] <= cell["draws"]):
                    bad.append(("accepts", kind, key))
    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"]]
    sr = {r: frac(cap, "single", r)[0] for r in RHOS}
    hr = {r: frac(hon, "single", r)[0] for r in RHOS}
    qr = {q: frac(cap, "quorum", q)[0] for q in QUORUMS}

    vals = [sr[r] for r in RHOS]
    h1 = monotone(vals) and vals[-1] > vals[0]
    h2 = abs(sr["0"]) < 1e-9 and abs(sr["1"] - 1) < 1e-9
    h3 = sr["0.5"] > 0
    h4 = abs(qr["1,0,0"]) < 1e-9 and abs(qr["1,1,0"] - 1) < 1e-9
    h6 = abs(hr["0"] - 1) < 1e-9 and abs(hr["1"]) < 1e-9
    rcap = [r for r in rep["sets"]["replication"]["rows"] if r["accepted"] and not r["correct"]]
    rr = [frac(rcap, "single", r)[0] for r in RHOS]
    h7 = (monotone(rr) and abs(rr[0]) < 1e-9 and abs(rr[-1] - 1) < 1e-9 and
          abs(frac(rcap, "quorum", "1,1,0")[0] - 1) < 1e-9)
    exp = {"H1_forgery_monotone_in_overlap": h1, "H2_endpoints": h2,
           "H3_partial_overlap_is_dangerous": h3, "H4_quorum_boundary": h4,
           "H6_liveness_cost": h6, "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 rates", all(abs(H["H1_forgery_monotone_in_overlap"]["rates"][r] - sr[r]) < 0.0002
                        for r in RHOS))
    ck("H2 endpoints", abs(H["H2_endpoints"]["rho_0"] - sr["0"]) < 0.0002 and
       abs(H["H2_endpoints"]["rho_1"] - sr["1"]) < 0.0002)
    ck("H3 counts", H["H3_partial_overlap_is_dangerous"]["forgeries"] ==
       frac(cap, "single", "0.5")[1] and
       H["H3_partial_overlap_is_dangerous"]["draws"] == frac(cap, "single", "0.5")[2])
    ck("H4 rates", abs(H["H4_quorum_boundary"]["one_of_three"] - qr["1,0,0"]) < 0.0002 and
       abs(H["H4_quorum_boundary"]["two_of_three"] - qr["1,1,0"]) < 0.0002)
    ck("H5 rates", all(abs(H["H5_partial_quorum"]["rates"][q] - qr[q]) < 0.0002 for q in QUORUMS))
    ck("H6 rates", all(abs(H["H6_liveness_cost"]["honest_accept_by_rho"][r] - hr[r]) < 0.0002
                        for r in RHOS))
    ck("H7 rates", all(abs(H["H7_replication"]["rates"][r] - rr[i]) < 0.0002
                        for i, r in enumerate(RHOS)))
    verdict = ("AUDIT_CORRELATION_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["honest_certificates"] == len(hon) and
       all(abs(f["single_forgery_by_overlap"][r] - sr[r]) < 0.0002 for r in RHOS) and
       all(abs(f["quorum_forgery"][q] - qr[q]) < 0.0002 for q in QUORUMS))
    ck("quorum boundary", qr["1,0,0"] == 0 and qr["1,1,0"] == 1)
    ck("certificates", len(acc) == rep["resources"]["certificates"] and len(acc) > 0)
    ck("decisions", rep["resources"]["decisions"] ==
       len(acc) * (len(RHOS) + len(QUORUMS)) * DRAWS)
    ck("manifest headline", man.get("headline", {}).get("verdict") == rep["verdict"] and
       man.get("headline", {}).get("runs") == 48 and
       man.get("headline", {}).get("certificates") == len(acc))

    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 / "E311_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.e311.verify.v1", "checks": len(c),
                      "passed": passed, "failed": [x for x in c if not x["ok"]],
                      "verdict": verdict, "single_forgery": {r: round(sr[r], 4) for r in RHOS},
                      "quorum_boundary": [round(qr["1,0,0"], 4), round(qr["1,1,0"], 4)]},
                     ensure_ascii=False))
    return 0 if passed == len(c) else 1


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