#!/usr/bin/env python3
"""Standalone E388 verifier — stdlib only, imports no CAIN code.

Recomputes every policy's safety (Q-1), zero-colluder margin (n-Q), conservation, and for each f < Q the
honest-failure margin (n-f-Q) and the binomial availability. Then H1-H6/H8, the pooled verdict, the dev
selection, the row chain, the salt commitments, the manifest signature, no unlisted files, no source.
"""
from __future__ import annotations

import hashlib
import json
import math
import sys
from pathlib import Path

FAILS = []
CHECKS = [0]
RECORDS = 32
POLICIES = (
    ("SINGLE", 1, 1), ("MAJ4", 4, 3), ("ALL4", 4, 4),
    ("MAJ7", 7, 4), ("BFT7", 7, 5), ("ALL7", 7, 7),
    ("MAJ10", 10, 6), ("BFT10", 10, 7), ("ALL10", 10, 10),
)
P_FAIL = ("0.01", "0.05", "0.10")


def ck(cond, name, detail=""):
    CHECKS[0] += 1
    if not cond:
        FAILS.append(f"{name}: {detail}")


def sha(b):
    return hashlib.sha256(b if isinstance(b, bytes) else b.encode()).hexdigest()


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


def binom_cdf(n, p, k):
    if k < 0:
        return 0.0
    if k >= n:
        return 1.0
    return sum(math.comb(n, i) * (p ** i) * ((1 - p) ** (n - i)) for i in range(k + 1))


def cell(n, Q):
    rows = {}
    for f in range(Q):
        margin = n - f - Q
        rows[str(f)] = {"margin": margin, "d_max": margin if margin >= 0 else 0,
                        "availability": {p: (binom_cdf(n - f, float(p), margin) if margin >= 0 else 0.0) for p in P_FAIL}}
    return {"n": n, "Q": Q, "safety": Q - 1, "margin0": n - Q,
            "conservation": (Q - 1) + (n - Q) == n - 1, "cost": Q, "rows": rows}


def main(d):
    b = Path(d)
    rep = json.loads((b / "E388_RUN_REPORT.json").read_text())
    pre = json.loads((b / "E388_PREREGISTRATION.json").read_text())
    man = json.loads((b / "E388_MANIFEST.json").read_text())
    freeze = json.loads((b / "E388_PREREGISTRATION_FREEZE.json").read_text())
    salts = json.loads((b / "E388_SALT_REVEALED.json").read_text())
    dev = json.loads((b / "E388_DEVIATIONS.json").read_text())

    ck(rep["schema"] == "cain42.e388.run.v1", "schema")
    ck(rep["evolution"] == "E388", "evolution")
    ck(rep["model_calls"] == 0 and rep["api_spend_usd"] == 0.0 and rep["weights_changed"] == 0, "zero resources")
    ck(sha((b / "E388_PREREGISTRATION.json").read_bytes()) == freeze["preregistration_sha256"], "prereg freeze hash")
    ck(pre["salt_commitment_sha256"] == rep["salt_commitment_sha256"], "salt commitment carried")
    for s in ("primary", "replication"):
        ck(sha(bytes.fromhex(salts[s])) == pre["salt_commitment_sha256"][s], f"salt {s} commitment")
        ck(len(bytes.fromhex(salts[s])) == 32, f"salt {s} 32 bytes")
    ck(dev.get("deviations") == [], "no deviations")

    insts = rep["instances"]
    ck(len(insts) == 24, "24 instances", len(insts))
    ck(sum(1 for x in insts if x["salt"] == "primary") == 12, "12 primary")
    ck(sum(1 for x in insts if x["salt"] == "replication") == 12, "12 replication")
    for x in insts:
        tag = x["id"]
        ck(x["records"] == RECORDS, f"{tag} records")
        ck(set(x["policies"]) == {p[0] for p in POLICIES}, f"{tag} policies")
        for name, nn, Q in POLICIES:
            want = cell(nn, Q)
            p = x["policies"][name]
            ck(p["n"] == nn and p["Q"] == Q and p["safety"] == want["safety"] and p["margin0"] == want["margin0"]
               and p["conservation"] is True and p["cost"] == Q, f"{tag} {name} meta")
            ck(set(p["rows"]) == {str(f) for f in range(Q)}, f"{tag} {name} rows")
            for f in range(Q):
                got = p["rows"][str(f)]
                w = want["rows"][str(f)]
                ck(got["margin"] == w["margin"] and got["d_max"] == w["d_max"], f"{tag} {name} f={f} margin")
                for pp in P_FAIL:
                    ck(abs(got["availability"][pp] - w["availability"][pp]) < 1e-12, f"{tag} {name} f={f} p={pp}")

    def sm(lst):
        n = len(lst)
        out = {"instances": n}
        for name, nn, Q in POLICIES:
            out[name] = {"n": nn, "Q": Q, "safety": Q - 1, "margin0": nn - Q, "cost": Q,
                         "rows": {f: {"margin": lst[0]["policies"][name]["rows"][f]["margin"],
                                      "d_max": lst[0]["policies"][name]["rows"][f]["d_max"],
                                      "availability": {pp: sum(x["policies"][name]["rows"][f]["availability"][pp] for x in lst) / n for pp in P_FAIL}}
                                  for f in lst[0]["policies"][name]["rows"]}}
        return out
    prim = [x for x in insts if x["salt"] == "primary"]
    repl = [x for x in insts if x["salt"] == "replication"]
    for label, lst in (("primary", prim), ("replication", repl), ("all", insts)):
        got, want = rep["summaries"][label], sm(lst)
        ck(got["instances"] == want["instances"], f"summary {label} instances")
        for name, _nn, _Q in POLICIES:
            for f, row in want[name]["rows"].items():
                ck(got[name]["rows"][f]["margin"] == row["margin"] and got[name]["rows"][f]["d_max"] == row["d_max"], f"summary {label} {name} f={f}")
                for pp in P_FAIL:
                    ck(abs(got[name]["rows"][f]["availability"][pp] - row["availability"][pp]) < 1e-12, f"summary {label} {name} f={f} {pp}")

    def ev(lst, sel):
        n = len(lst)
        h1 = sum(1 for x in lst if all(x["policies"][name]["safety"] == Q - 1 for name, _nn, Q in POLICIES))
        h2 = sum(1 for x in lst for name, nn, Q in POLICIES for f in range(Q)
                 if x["policies"][name]["rows"][str(f)]["d_max"] == max(0, nn - f - Q))
        h2tot = n * sum(Q for _name, _nn, Q in POLICIES)
        h3 = sum(1 for x in lst if all(x["policies"][name]["conservation"] for name, _nn, _Q in POLICIES))
        h4 = sum(1 for x in lst if all(x["policies"][name]["rows"][str(f)]["d_max"] == 0
                                       for name, nn, Q in (("MAJ4", 4, 3), ("BFT7", 7, 5), ("BFT10", 10, 7))
                                       for f in (Q - 2,) if f >= 0))
        h5 = sum(1 for x in lst if
                 all(x["policies"]["MAJ7"]["rows"]["2"]["availability"][pp] > x["policies"]["BFT7"]["rows"]["2"]["availability"][pp] for pp in P_FAIL)
                 and all(x["policies"]["MAJ10"]["rows"]["2"]["availability"][pp] > x["policies"]["BFT10"]["rows"]["2"]["availability"][pp] for pp in P_FAIL))
        def margin2(nm):
            return x["policies"][nm]["rows"].get("2", {"margin": -10**9})["margin"]
        h8 = sum(1 for x in lst if (sel in x["policies"] and x["policies"][sel]["safety"] >= 2 and margin2(sel) >= 1
                                    and x["policies"][sel]["cost"] == min(x["policies"][nm]["cost"] for nm, _nn, _Q in POLICIES
                                                                          if x["policies"][nm]["safety"] >= 2 and margin2(nm) >= 1)))
        return {
            "H1_safety_is_q_minus_one": ("SUPPORTED" if h1 == n else "NOT_SUPPORTED", h1),
            "H2_liveness_margin": ("SUPPORTED" if h2 == h2tot else "NOT_SUPPORTED", h2),
            "H3_conservation_law": ("SUPPORTED" if h3 == n else "NOT_SUPPORTED", h3),
            "H4_bft_has_no_liveness_margin": ("SUPPORTED" if h4 == n else "NOT_SUPPORTED", h4),
            "H5_majority_is_more_available": ("SUPPORTED" if h5 == n else "NOT_SUPPORTED", h5),
            "H8_dev_selection": ("SUPPORTED" if (sel == "MAJ7" and h8 == n) else "NOT_SUPPORTED", h8),
        }
    for label, lst in (("primary", prim), ("replication", repl)):
        for k, (v, _) in ev(lst, rep["selection"]["selected"]).items():
            got = rep["hypotheses" if label == "primary" else "replication_hypotheses"][k]["verdict"]
            ck(got == v, f"{label} {k}", f"{got} vs {v}")
    ok = all(v == "SUPPORTED" for k, (v, _) in ev(prim, rep["selection"]["selected"]).items())
    rep_ok = all(v == "SUPPORTED" for k, (v, _) in ev(repl, rep["selection"]["selected"]).items())
    ck(rep["verdict"] == ("QUORUM_SAFETY_LIVENESS_FRONTIER_SUPPORTED" if (ok and rep_ok) else "NOT_SUPPORTED"), "pooled verdict")
    ck(rep["replication_verdict"] == ("SUPPORTED" if rep_ok else "NOT_SUPPORTED"), "replication verdict")
    ck(rep["hypotheses"]["H6_replication"]["verdict"] == ("SUPPORTED" if rep_ok else "NOT_SUPPORTED"), "H6 derived")
    ck(rep["hypotheses"]["H7_external_review"]["verdict"] == "BLOCKED", "H7 blocked")

    rows = []
    for name, nn, Q in POLICIES:
        rows.append({"policy": name, "n": nn, "Q": Q, "safety": Q - 1, "cost": Q,
                     "margin_at_f2": rep["dev_instances"][0]["policies"][name]["rows"].get("2", {"margin": -10**9})["margin"]})
    pub = {c["policy"]: c for c in rep["selection"]["candidates"]}
    for r in rows:
        ck(pub[r["policy"]]["safety"] == r["safety"] and pub[r["policy"]]["cost"] == r["cost"]
           and pub[r["policy"]]["margin_at_f2"] == r["margin_at_f2"], f"selection candidate {r['policy']}")
    eligible = [r for r in rows if r["safety"] >= 2 and r["margin_at_f2"] >= 1]
    eligible.sort(key=lambda r: (r["cost"], r["n"], r["policy"]))
    ck(eligible[0]["policy"] == rep["selection"]["selected"], "selection recomputed")

    prev = "0" * 64
    for i, x in enumerate(insts):
        hh = sha((prev + sha(canon(x))).encode())
        ck(rep["chain"][i]["prev"] == prev and rep["chain"][i]["hash"] == hh, f"chain {i}")
        prev = hh

    ck(man["merkle_root"] == (b / "MERKLE_ROOT.txt").read_text().strip(), "merkle file")
    files = man["files"]
    leaves = sorted(files.values())
    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)]
    ck(leaves[0] == man["merkle_root"], "merkle recompute")
    for rel, dig in files.items():
        p = b / rel
        ck(p.exists() and sha(p.read_bytes()) == dig, f"file digest {rel}")
    body = {k: v for k, v in man.items() if k != "signature"}
    try:
        from cryptography.hazmat.primitives import serialization
        pubk = serialization.load_pem_public_key((b / "E388_PUBKEY.pem").read_bytes())
        pubk.verify(bytes.fromhex(man["signature"]), canon(body))
        ck(True, "manifest signature")
    except Exception as e:  # noqa: BLE001
        ck(False, "manifest signature", str(e)[:120])
    ck(man["headline"]["verdict"] == rep["verdict"], "headline verdict")
    ck(man["headline"]["model_calls"] == 0, "headline model calls")
    ck(man["headline"]["external_review"] == "NOT_OBTAINED", "headline external review")
    disk = {str(p.relative_to(b)) for p in b.rglob("*") if p.is_file()
            and str(p.relative_to(b)) not in
            {"E388_MANIFEST.json", "E388_SIGNED_BODY.json", "E388_TAMPER_RESULTS.json",
             "E388_VERIFICATION_RESULTS.json", "MANIFEST.json", "MERKLE_ROOT.txt",
             "PUBLICATION.json", "E388_OMEGA_SEAL.json"}
            and "__pycache__" not in p.parts and not p.name.endswith(("-wal", "-shm"))}
    ck(disk == set(files), "no unlisted files", str(sorted(disk - set(files))[:3]))
    ck(not any(p.name == "run.py" for p in b.rglob("*")), "no engine source")

    print(f"{CHECKS[0] - len(FAILS)}/{CHECKS[0]} checks passed")
    if FAILS:
        for f in FAILS[:40]:
            print("FAIL", f)
        return 1
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1]))
