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

Recomputes every policy's margin, independent availability (binomial CDF), common-mode term and the
mixture (1-rho)*ind + rho*cm. Then H1-H6/H8, the pooled verdict, the dev selection, the row chain, the
salt commitments, D1, the manifest signature, no unlisted files and no engine source.
"""
from __future__ import annotations

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

FAILS = []
CHECKS = [0]
RECORDS = 32
POLICIES = (("MAJ4", 4, 3), ("MAJ7", 7, 4), ("BFT7", 7, 5), ("MAJ10", 10, 6), ("BFT10", 10, 7), ("ALL10", 10, 10))
F = 2
P_FAIL = (0.01, 0.05, 0.10)
RHO = (0.0, 0.25, 0.5, 0.75, 1.0)


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):
    margin = n - F - Q
    ind = {f"{p:.2f}": (binom_cdf(n - F, p, margin) if margin >= 0 else 0.0) for p in P_FAIL}
    cm = 1.0 if margin >= n - F else 0.0
    avail = {f"{r:.2f}": {f"{p:.2f}": (1 - r) * ind[f"{p:.2f}"] + r * cm for p in P_FAIL} for r in RHO}
    return {"n": n, "Q": Q, "f": F, "margin": margin, "safety": Q - 1, "cost": Q,
            "independent": ind, "common_mode": cm, "availability": avail}


def main(d):
    b = Path(d)
    rep = json.loads((b / "E389_RUN_REPORT.json").read_text())
    pre = json.loads((b / "E389_PREREGISTRATION.json").read_text())
    man = json.loads((b / "E389_MANIFEST.json").read_text())
    freeze = json.loads((b / "E389_PREREGISTRATION_FREEZE.json").read_text())
    salts = json.loads((b / "E389_SALT_REVEALED.json").read_text())
    dev = json.loads((b / "E389_DEVIATIONS.json").read_text())

    ck(rep["schema"] == "cain42.e389.run.v1", "schema")
    ck(rep["evolution"] == "E389", "evolution")
    ck(rep["model_calls"] == 0 and rep["api_spend_usd"] == 0.0 and rep["weights_changed"] == 0, "zero resources")
    ck(sha((b / "E389_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(len(dev.get("deviations", [])) == 1 and dev["deviations"][0]["id"] == "D1", "D1 recorded")

    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:
            p = x["policies"][name]
            want = cell(nn, Q)
            ck(p["n"] == nn and p["Q"] == Q and p["margin"] == want["margin"] and p["safety"] == Q - 1
               and p["cost"] == Q and p["common_mode"] == want["common_mode"], f"{tag} {name} meta")
            for pp in (f"{q:.2f}" for q in P_FAIL):
                ck(abs(p["independent"][pp] - want["independent"][pp]) < 1e-12, f"{tag} {name} ind {pp}")
            for r in (f"{q:.2f}" for q in RHO):
                for pp in (f"{q:.2f}" for q in P_FAIL):
                    ck(abs(p["availability"][r][pp] - want["availability"][r][pp]) < 1e-12, f"{tag} {name} {r} {pp}")

    def sm(lst):
        n = len(lst)
        out = {"instances": n}
        for name, nn, Q in POLICIES:
            out[name] = {"n": nn, "Q": Q, "f": F, "margin": nn - F - Q, "safety": Q - 1, "cost": Q,
                         "availability": {r: {pp: sum(x["policies"][name]["availability"][r][pp] for x in lst) / n
                                              for pp in (f"{q:.2f}" for q in P_FAIL)}
                                          for r in (f"{q:.2f}" for q in RHO)}}
        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 r in want[name]["availability"]:
                for pp in want[name]["availability"][r]:
                    ck(abs(got[name]["availability"][r][pp] - want[name]["availability"][r][pp]) < 1e-12, f"summary {label} {name} {r} {pp}")
            ck(got[name]["margin"] == want[name]["margin"] and got[name]["safety"] == want[name]["safety"], f"summary {label} {name} meta")

    def ev(lst, sel):
        n = len(lst)
        h1 = sum(1 for x in lst if all(abs(x["policies"][name]["availability"]["0.00"][f"{p:.2f}"] - x["policies"][name]["independent"][f"{p:.2f}"]) < 1e-12
                                       for name, _nn, _Q in POLICIES for p in P_FAIL))
        h2 = sum(1 for x in lst for name, _nn, _Q in POLICIES for r in (f"{q:.2f}" for q in RHO)
                 if all(abs(x["policies"][name]["availability"][r][f"{p:.2f}"]
                            - ((1 - float(r)) * x["policies"][name]["independent"][f"{p:.2f}"] + float(r) * x["policies"][name]["common_mode"])) < 1e-12
                        for p in P_FAIL))
        h2tot = n * len(POLICIES) * len(RHO)
        h3 = sum(1 for x in lst if all(
            x["policies"]["MAJ7"]["availability"][r]["0.05"] - x["policies"]["BFT7"]["availability"][r]["0.05"]
            <= x["policies"]["MAJ7"]["availability"]["0.00"]["0.05"] - x["policies"]["BFT7"]["availability"]["0.00"]["0.05"] + 1e-12
            for r in (f"{q:.2f}" for q in RHO))
            and abs(x["policies"]["MAJ7"]["availability"]["1.00"]["0.05"] - x["policies"]["BFT7"]["availability"]["1.00"]["0.05"]) < 1e-12)
        h4 = sum(1 for x in lst if all(x["policies"][name]["availability"]["1.00"][f"{p:.2f}"] == 0.0
                                       for name, _nn, _Q in POLICIES for p in P_FAIL))
        h5 = sum(1 for x in lst if all(x["policies"][name]["safety"] == Q - 1 for name, _nn, Q in POLICIES)
                 and all(x["policies"][name]["availability"]["0.50"][f"{p:.2f}"] <= x["policies"][name]["availability"]["0.00"][f"{p:.2f}"] + 1e-12
                         for name, _nn, _Q in POLICIES for p in P_FAIL))
        h8 = sum(1 for x in lst if (sel in x["policies"] and x["policies"][sel]["margin"] >= 0
                                    and x["policies"][sel]["availability"]["0.50"]["0.05"]
                                    == max(x["policies"][nm]["availability"]["0.50"]["0.05"] for nm, _n2, _Q2 in POLICIES
                                           if x["policies"][nm]["margin"] >= 0)))
        return {
            "H1_independent_limit_reproduced": ("SUPPORTED" if h1 == n else "NOT_SUPPORTED", h1),
            "H2_correlation_formula": ("SUPPORTED" if h2 == h2tot else "NOT_SUPPORTED", h2),
            "H3_majority_gap_shrinks": ("SUPPORTED" if h3 == n else "NOT_SUPPORTED", h3),
            "H4_common_mode_kills_all": ("SUPPORTED" if h4 == n else "NOT_SUPPORTED", h4),
            "H5_safety_unchanged_liveness_collapses": ("SUPPORTED" if h5 == n else "NOT_SUPPORTED", h5),
            "H8_dev_selection": ("SUPPORTED" if (sel == "MAJ10" 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"] == ("CORRELATED_FAILURE_LIMIT_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, "cost": Q, "safety": Q - 1, "margin": nn - F - Q,
                     "availability": rep["dev_instances"][0]["policies"][name]["availability"]["0.50"]["0.05"]})
    pub = {c["policy"]: c for c in rep["selection"]["candidates"]}
    for r in rows:
        ck(pub[r["policy"]]["margin"] == r["margin"] and pub[r["policy"]]["cost"] == r["cost"]
           and abs(pub[r["policy"]]["availability"] - r["availability"]) < 1e-12, f"selection candidate {r['policy']}")
    eligible = [r for r in rows if r["margin"] >= 0]
    eligible.sort(key=lambda r: (-r["availability"], r["cost"], 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 / "E389_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
            {"E389_MANIFEST.json", "E389_SIGNED_BODY.json", "E389_TAMPER_RESULTS.json",
             "E389_VERIFICATION_RESULTS.json", "MANIFEST.json", "MERKLE_ROOT.txt",
             "PUBLICATION.json", "E389_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]))
