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

Recomputes from the published per-instance rows:
  R = 256 - m, K = ceil(R/32), the start-averaged bracket [1-(1-1/K)^w, min(1,w/K)] for the
  without-replacement per-cycle sweep, the exact 1-(1-32/R)^w for the with-replacement lease,
  every arm's structural invariants, H1-H5/H8 on primary and replication, the pooled verdict,
  the v1 near-miss (H3/H6 NOT_SUPPORTED), the row chain, the salt commitments (fresh vs v1),
  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]
ARMS = ("SWEEP_TIMED", "SWEEP_BLIND", "SECRET_SWEEP", "LEASE32", "TARGETED", "FULL")
WINDOWS = (("W1", 1), ("W5", 5), ("W30", 30), ("PERSISTENT", None))
BUDGET = 32
USES = 60
COST_CAP = 0.15


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


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


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


def bracket(p, w, uses, replacement=True):
    lo = hi = 0.0
    for s in range(uses):
        w_eff = uses - s if w is None else min(w, uses - s)
        base = 1.0 - (1.0 - p) ** w_eff
        lo += base / uses
        hi += (base if replacement else min(1.0, w_eff * p)) / uses
    return lo, hi


def main(d):
    b = Path(d)
    rep = json.loads((b / "E372T_RUN_REPORT.json").read_text())
    pre = json.loads((b / "E372T_PREREGISTRATION.json").read_text())
    man = json.loads((b / "E372T_MANIFEST.json").read_text())
    freeze = json.loads((b / "E372T_PREREGISTRATION_FREEZE.json").read_text())
    salts = json.loads((b / "E372T_SALT_REVEALED.json").read_text())
    dev = json.loads((b / "E372T_DEVIATIONS.json").read_text())
    v1 = json.loads((b / "E372T_RUN_REPORT.v1.json").read_text())
    v1_pre = json.loads((b / "E372T_PREREGISTRATION.v1.json").read_text())

    ck(rep["schema"] == "cain42.e372t.run.v1", "schema")
    ck(rep["evolution"] == "E372-T", "evolution")
    ck(rep["model_calls"] == 0 and rep["api_spend_usd"] == 0.0 and rep["weights_changed"] == 0, "zero resources")
    ck(sha((b / "E372T_PREREGISTRATION.json").read_bytes()) == freeze["preregistration_sha256"], "prereg freeze hash")
    ck(freeze["schema"] == "cain42.e372t.freeze.v2", "freeze v2")
    ck(pre.get("version") == 2 and pre.get("supersedes") == "E372T_PREREGISTRATION.v1.json", "prereg v2")
    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(sha(bytes.fromhex(salts[s])) != v1_pre["salt_commitment_sha256"][s], f"salt {s} fresh vs v1")
    ck(len(dev["deviations"]) == 1 and dev["deviations"][0]["id"] == "D1", "D1 recorded")
    ck("specification" in dev["deviations"][0]["kind"], "D1 specification")
    ck(v1["verdict"] == "NOT_SUPPORTED", "v1 near-miss preserved", v1["verdict"])
    ck(v1["hypotheses"].get("H3_secret_sweep_matches_sampling", {}).get("verdict") == "NOT_SUPPORTED", "v1 H3 miss")
    ck(v1["hypotheses"]["H6_replication"]["verdict"] == "NOT_SUPPORTED", "v1 H6 miss")

    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")
    ck({x["cond"] for x in insts} == {"T2_K2", "T3_K3"}, "both conditions")
    for x in insts:
        tag = x["id"]
        R, K = x["R"], x["K"]
        ck(R == 256 - x["m"], f"{tag} R")
        ck(K == math.ceil(R / BUDGET), f"{tag} K")
        ck(x["class_sound"] is True, f"{tag} class sound")
        ck(set(x["arms"]) == {w for w, _ in WINDOWS}, f"{tag} windows")
        for name0, _w0 in WINDOWS:
            ck(set(x["arms"][name0]) == set(ARMS), f"{tag} {name0} arms")
        for name, w in WINDOWS:
            lo, hi = bracket(1.0 / K, w, USES, replacement=False)
            ck(abs(x["bracket"][name]["lo"] - lo) < 1e-12 and abs(x["bracket"][name]["hi"] - hi) < 1e-12,
               f"{tag} {name} bracket")
            llo, lhi = bracket(BUDGET / R, w, USES, replacement=True)
            ck(abs(x["lease_bracket"][name]["lo"] - llo) < 1e-12 and abs(x["lease_bracket"][name]["hi"] - lhi) < 1e-12,
               f"{tag} {name} lease bracket")
            for arm in ARMS:
                a = x["arms"][name][arm]
                ck(0.0 <= a["caught_rate"] <= 1.0, f"{tag} {name} {arm} caught range")
                ck(a["mean_wrong"] >= 0.0, f"{tag} {name} {arm} wrong non-negative")
            ck(x["arms"][name]["TARGETED"]["caught_rate"] == 1.0 and x["arms"][name]["TARGETED"]["mean_wrong"] == 0.0
               and x["arms"][name]["TARGETED"]["cost"] == 1.0, f"{tag} {name} targeted exact")
            ck(x["arms"][name]["FULL"]["mean_wrong"] == 0.0 and x["arms"][name]["FULL"]["cost"] == 256.0,
               f"{tag} {name} full exact")
        ck(x["arms"]["W1"]["SWEEP_TIMED"]["caught_rate"] == 0.0 and x["arms"]["W1"]["SWEEP_TIMED"]["mean_wrong"] == 1.0,
           f"{tag} W1 timed blind")
        ck(x["arms"]["W5"]["SWEEP_TIMED"]["caught_rate"] == 0.0 and x["arms"]["W5"]["SWEEP_TIMED"]["mean_wrong"] == 5.0,
           f"{tag} W5 timed blind")
        ck(x["arms"]["PERSISTENT"]["SWEEP_TIMED"]["caught_rate"] == 1.0
           and x["arms"]["PERSISTENT"]["SWEEP_TIMED"]["mean_wrong"] <= K - 1, f"{tag} persistent caught")

    def sm(lst):
        n = len(lst)
        out = {"instances": n, "mean_m": sum(x["m"] for x in lst) / n, "mean_R": sum(x["R"] for x in lst) / n,
               "mean_K": sum(x["K"] for x in lst) / n, "class_sound": sum(1 for x in lst if x["class_sound"])}
        for name, _w in WINDOWS:
            out[name] = {a: {"caught_rate": sum(x["arms"][name][a]["caught_rate"] for x in lst) / n,
                             "mean_wrong": sum(x["arms"][name][a]["mean_wrong"] for x in lst) / n,
                             "cost": sum(x["arms"][name][a]["cost"] for x in lst) / n} for a in ARMS}
        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)
        for k, v in want.items():
            if isinstance(v, dict):
                for arm in ARMS:
                    for kk in ("caught_rate", "mean_wrong", "cost"):
                        ck(abs(got[k][arm][kk] - v[arm][kk]) < 1e-12, f"summary {label} {k} {arm} {kk}")
            else:
                ck(got[k] == v, f"summary {label} {k}", f"{got[k]} vs {v}")

    def ev(lst, sel):
        n = len(lst)

        def g(x, win, arm, key):
            return x["arms"][win][arm][key]

        def inb(x, win):
            b_ = x["bracket"][win]
            v = g(x, win, "SECRET_SWEEP", "caught_rate")
            return b_["lo"] - 0.06 <= v <= b_["hi"] + 0.06
        h1a = sum(1 for x in lst if g(x, "W1", "SWEEP_TIMED", "caught_rate") == 0 and g(x, "W1", "SWEEP_TIMED", "mean_wrong") == 1)
        h1b = sum(1 for x in lst if g(x, "W5", "SWEEP_TIMED", "caught_rate") == 0 and g(x, "W5", "SWEEP_TIMED", "mean_wrong") == 5)
        h2 = sum(1 for x in lst if g(x, "PERSISTENT", "SWEEP_TIMED", "caught_rate") == 1 and g(x, "PERSISTENT", "SWEEP_TIMED", "mean_wrong") <= x["K"] - 1)
        h3a, h3b = sum(1 for x in lst if inb(x, "W1")), sum(1 for x in lst if inb(x, "W5"))
        h3c = sum(1 for x in lst if 0.0 < g(x, "W1", "SECRET_SWEEP", "caught_rate") < 1.0)
        h3d = sum(1 for x in lst if g(x, "W1", "SECRET_SWEEP", "caught_rate") < g(x, "W5", "SECRET_SWEEP", "caught_rate")
                  <= g(x, "W30", "SECRET_SWEEP", "caught_rate"))
        h4a = sum(1 for x in lst if abs(g(x, "W1", "LEASE32", "caught_rate") - x["lease_bracket"]["W1"]["lo"]) <= 0.10)
        h4b = sum(1 for x in lst if abs(g(x, "W5", "LEASE32", "caught_rate") - x["lease_bracket"]["W5"]["lo"]) <= 0.10)
        h5 = sum(1 for x in lst for name, _w in WINDOWS if g(x, name, "TARGETED", "caught_rate") == 1
                 and g(x, name, "TARGETED", "mean_wrong") == 0 and g(x, name, "TARGETED", "cost") == 1)
        h5f = sum(1 for x in lst for name, _w in WINDOWS if g(x, name, "FULL", "mean_wrong") == 0)
        h8a = sum(1 for x in lst if g(x, "W1", sel, "mean_wrong") <= min(g(x, "W1", a, "mean_wrong")
                                                                       for a in ARMS if g(x, "W1", a, "cost") / 256 <= COST_CAP))
        h8b = sum(1 for x in lst if g(x, "W1", sel, "cost") / 256 <= COST_CAP)
        return {
            "H1_timed_sweep_is_blind": ("SUPPORTED" if (h1a == n and h1b == n) else "NOT_SUPPORTED", h1a),
            "H2_persistent_is_the_control": ("SUPPORTED" if h2 == n else "NOT_SUPPORTED", h2),
            "H3_secret_sweep_without_replacement": ("SUPPORTED" if (h3a >= math.ceil(0.9 * n) and h3b >= math.ceil(0.9 * n)
                                                                   and h3c >= math.ceil(0.9 * n) and h3d >= math.ceil(0.9 * n)) else "NOT_SUPPORTED", h3b),
            "H4_lease_matches_sampling": ("SUPPORTED" if (h4a >= math.ceil(0.9 * n) and h4b >= math.ceil(0.9 * n)) else "NOT_SUPPORTED", h4b),
            "H5_boundary_check_is_exact": ("SUPPORTED" if (h5 == n * len(WINDOWS) and h5f == n * len(WINDOWS)) else "NOT_SUPPORTED", h5),
            "H8_dev_selection": ("SUPPORTED" if (sel == "TARGETED" and h8a == n and h8b == n) else "NOT_SUPPORTED", h8a),
        }
    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"] == ("BOUNDARY_CHECK_DOMINATES" 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 a in ARMS:
        cost = sum(y["arms"]["W1"][a]["cost"] for y in rep["dev_instances"]) / len(rep["dev_instances"])
        wrong = sum(y["arms"]["W1"][a]["mean_wrong"] + y["arms"]["PERSISTENT"][a]["mean_wrong"] for y in rep["dev_instances"]) / (2 * len(rep["dev_instances"]))
        rows.append({"arm": a, "mean_wrong": wrong, "mean_cost": cost, "cost_ratio": cost / 256})
    pub = {c["arm"]: c for c in rep["selection"]["candidates"]}
    for r in rows:
        ck(r["arm"] in pub, f"selection candidate {r['arm']}")
        if r["arm"] in pub:
            for k in ("mean_wrong", "mean_cost", "cost_ratio"):
                ck(abs(pub[r["arm"]][k] - r[k]) < 1e-12, f"selection candidate {r['arm']} {k}")
    eligible = [r for r in rows if r["cost_ratio"] <= COST_CAP]
    eligible.sort(key=lambda r: (round(r["mean_wrong"], 9), round(r["mean_cost"], 9), ARMS.index(r["arm"])))
    ck(eligible[0]["arm"] == 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
        pub = serialization.load_pem_public_key((b / "E372T_PUBKEY.pem").read_bytes())
        pub.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
            {"E372T_MANIFEST.json", "E372T_SIGNED_BODY.json", "E372T_TAMPER_RESULTS.json",
             "E372T_VERIFICATION_RESULTS.json", "MANIFEST.json", "MERKLE_ROOT.txt",
             "PUBLICATION.json", "E372T_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]))
