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

Recomputes every cell exactly (closed form over the window start):
  cycle = ceil(k/32), p_used = min(32,k)/k, p_world = 32/256
  sampled arms: (wrong, caught) = start-averaged failures before the detecting use and catch probability
  rotation arm: the timed worst gap over the used-set cycle
  USED_ALL: 0 wrong at cost k; FULL: 0 wrong at 256
then every hypothesis H1-H5/H8 on primary and replication, the pooled verdict, the dev-only selection,
the v1 near-miss (H2/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]
K_VALUES = (2, 8, 32, 64)
WINDOWS = (("W1", 1), ("W5", 5), ("PERSISTENT", None))
ARMS = ("USED_ALL", "USED_SAMPLE32", "USED_ROTATE32", "WORLD_32", "FULL")
BUDGET = 32
USES = 60
COST_MULT = 1.10


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 sampled_wrong(p, w, uses):
    tw = tc = 0.0
    for s in range(uses):
        w_eff = uses - s if w is None else min(w, uses - s)
        caught = 1.0 - (1.0 - p) ** w_eff
        tw += ((1.0 - p) * caught / p) if p > 0 else w_eff
        tc += caught
    return tw / uses, tc / uses


def rotate_timed(c, w, uses):
    worst, caught = -1, False
    for start in range(uses):
        w_eff = uses - start if w is None else min(w, uses - start)
        gap = (c - (start % c)) % c
        if start + gap >= uses:
            wr, ct = uses - start, False
        elif gap >= w_eff:
            wr, ct = w_eff, False
        else:
            wr, ct = gap, True
        if wr > worst or (wr == worst and ct):
            worst, caught = wr, ct
    return worst, caught


def main(d):
    b = Path(d)
    rep = json.loads((b / "E375_RUN_REPORT.json").read_text())
    pre = json.loads((b / "E375_PREREGISTRATION.json").read_text())
    man = json.loads((b / "E375_MANIFEST.json").read_text())
    freeze = json.loads((b / "E375_PREREGISTRATION_FREEZE.json").read_text())
    salts = json.loads((b / "E375_SALT_REVEALED.json").read_text())
    dev = json.loads((b / "E375_DEVIATIONS.json").read_text())
    v1 = json.loads((b / "E375_RUN_REPORT.v1.json").read_text())
    v1_pre = json.loads((b / "E375_PREREGISTRATION.v1.json").read_text())

    ck(rep["schema"] == "cain42.e375.run.v1", "schema")
    ck(rep["evolution"] == "E375", "evolution")
    ck(rep["model_calls"] == 0 and rep["api_spend_usd"] == 0.0 and rep["weights_changed"] == 0, "zero resources")
    ck(sha((b / "E375_PREREGISTRATION.json").read_bytes()) == freeze["preregistration_sha256"], "prereg freeze hash")
    ck(freeze["schema"] == "cain42.e375.freeze.v2", "freeze v2")
    ck(pre.get("version") == 2 and pre.get("supersedes") == "E375_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("implementation" in dev["deviations"][0]["kind"], "D1 implementation")
    ck(v1["verdict"] == "NOT_SUPPORTED", "v1 near-miss preserved", v1["verdict"])
    ck(v1["hypotheses"]["H2_32_covers_a_small_used_set"]["verdict"] == "NOT_SUPPORTED", "v1 H2 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"]
        ck(x["R"] == 256 - x["m"], f"{tag} R")
        ck(x["class_sound"] is True, f"{tag} class sound")
        ck(set(x["cells"]) == {str(k) for k in K_VALUES}, f"{tag} cells")
        for k in K_VALUES:
            key = str(k)
            c = math.ceil(k / BUDGET)
            p_used = min(BUDGET, k) / k
            p_world = BUDGET / 256
            cell = x["cells"][key]
            ck(cell["k"] == k and cell["cycle"] == c, f"{tag} k={k} meta")
            ck(abs(cell["p_used"] - p_used) < 1e-15 and abs(cell["p_world"] - p_world) < 1e-15, f"{tag} k={k} p")
            ck(set(cell["windows"]) == {w for w, _ in WINDOWS}, f"{tag} k={k} windows")
            for name, w in WINDOWS:
                win = cell["windows"][name]
                ck(set(win) == set(ARMS), f"{tag} k={k} {name} arms")
                ck(abs(win["USED_ALL"]["mean_wrong"]) < 1e-15 and win["USED_ALL"]["caught_rate"] == 1.0
                   and win["USED_ALL"]["cost"] == k, f"{tag} k={k} {name} used_all")
                sw, sc = sampled_wrong(p_used, w, USES)
                ck(abs(win["USED_SAMPLE32"]["mean_wrong"] - sw) < 1e-12
                   and abs(win["USED_SAMPLE32"]["caught_rate"] - sc) < 1e-12
                   and win["USED_SAMPLE32"]["cost"] == min(BUDGET, k), f"{tag} k={k} {name} sample")
                rw, rc = rotate_timed(c, w, USES)
                ck(win["USED_ROTATE32"]["mean_wrong"] == float(rw)
                   and win["USED_ROTATE32"]["caught_rate"] == (1.0 if rc else 0.0)
                   and win["USED_ROTATE32"]["cost"] == min(BUDGET, k), f"{tag} k={k} {name} rotate")
                ww, wc = sampled_wrong(p_world, w, USES)
                ck(abs(win["WORLD_32"]["mean_wrong"] - ww) < 1e-12 and abs(win["WORLD_32"]["caught_rate"] - wc) < 1e-12
                   and win["WORLD_32"]["cost"] == BUDGET, f"{tag} k={k} {name} world")
                ck(win["FULL"]["mean_wrong"] == 0.0 and win["FULL"]["caught_rate"] == 1.0
                   and win["FULL"]["cost"] == 256, f"{tag} k={k} {name} full")

    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,
               "class_sound": sum(1 for x in lst if x["class_sound"])}
        for k in K_VALUES:
            key = str(k)
            out[key] = {name: {a: {"caught_rate": sum(x["cells"][key]["windows"][name][a]["caught_rate"] for x in lst) / n,
                                   "mean_wrong": sum(x["cells"][key]["windows"][name][a]["mean_wrong"] for x in lst) / n,
                                   "cost": sum(x["cells"][key]["windows"][name][a]["cost"] for x in lst) / n}
                               for a in ARMS} for name, _w in WINDOWS}
        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 in K_VALUES:
            key = str(k)
            for name, _w in WINDOWS:
                for a in ARMS:
                    for kk in ("caught_rate", "mean_wrong", "cost"):
                        ck(abs(got[key][name][a][kk] - want[key][name][a][kk]) < 1e-12, f"summary {label} {key} {name} {a} {kk}")
        for kk in ("instances", "mean_m", "mean_R", "class_sound"):
            ck(got[kk] == want[kk], f"summary {label} {kk}")

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

        def g(x, k, win, arm, key):
            return x["cells"][str(k)]["windows"][win][arm][key]
        h1 = sum(1 for x in lst for k in K_VALUES for name, _w in WINDOWS
                 if g(x, k, name, "USED_ALL", "caught_rate") == 1.0 and g(x, k, name, "USED_ALL", "mean_wrong") == 0.0)
        h2 = sum(1 for x in lst for k in (2, 8, 32) for name, _w in WINDOWS
                 if g(x, k, name, "USED_SAMPLE32", "mean_wrong") == 0.0 and g(x, k, name, "USED_ROTATE32", "mean_wrong") == 0.0)
        h3a = sum(1 for x in lst if abs(g(x, 64, "W1", "USED_SAMPLE32", "caught_rate") - 0.5) <= 0.01)
        h3b = sum(1 for x in lst if abs(g(x, 64, "PERSISTENT", "USED_SAMPLE32", "mean_wrong") - 1.0) <= 0.10)
        h4a = sum(1 for x in lst if g(x, 64, "W1", "USED_ROTATE32", "caught_rate") == 0.0 and g(x, 64, "W1", "USED_ROTATE32", "mean_wrong") == 1.0)
        h4b = sum(1 for x in lst if all(g(x, k, "W1", "USED_ROTATE32", "mean_wrong") == 0.0 for k in (2, 8, 32)))
        h4c = sum(1 for x in lst if all(g(x, k, "PERSISTENT", "USED_ROTATE32", "caught_rate") == 1.0 for k in K_VALUES))
        h5 = sum(1 for x in lst for k in K_VALUES
                 if g(x, k, "W1", "USED_SAMPLE32", "caught_rate") >= 4.0 * g(x, k, "W1", "WORLD_32", "caught_rate"))
        h8a = sum(1 for x in lst if all(g(x, k, "W1", sel, "mean_wrong") <= min(g(x, k, "W1", a, "mean_wrong") for a in ARMS) for k in K_VALUES))
        h8b = sum(1 for x in lst if all(g(x, k, "W1", sel, "cost") <= COST_MULT * k for k in K_VALUES))
        return {
            "H1_used_set_is_exact": ("SUPPORTED" if h1 == n * len(K_VALUES) * len(WINDOWS) else "NOT_SUPPORTED", h1),
            "H2_32_covers_a_small_used_set": ("SUPPORTED" if h2 == n * 3 * len(WINDOWS) else "NOT_SUPPORTED", h2),
            "H3_partial_used_is_sampling": ("SUPPORTED" if (h3a == n and h3b == n) else "NOT_SUPPORTED", h3b),
            "H4_used_rotation_shortens_the_cycle": ("SUPPORTED" if (h4a == n and h4b == n and h4c == n) else "NOT_SUPPORTED", h4a),
            "H5_scoping_beats_the_world": ("SUPPORTED" if h5 == n * len(K_VALUES) else "NOT_SUPPORTED", h5),
            "H8_dev_selection": ("SUPPORTED" if (sel == "USED_ALL" 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"] == ("USED_SET_LAW_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 a in ARMS:
        wrong = sum(y["cells"][str(k)]["W1"][a]["mean_wrong"] + y["cells"][str(k)]["PERSISTENT"][a]["mean_wrong"]
                    for y in rep["dev_instances"] for k in (8, 64)) / (2 * 2 * len(rep["dev_instances"]))
        cost = sum(y["cells"][str(k)]["W1"][a]["cost"] for y in rep["dev_instances"] for k in (8, 64)) / (2 * len(rep["dev_instances"]))
        rows.append({"arm": a, "mean_wrong": wrong, "mean_cost": cost})
    pub = {c["arm"]: c for c in rep["selection"]["candidates"]}
    for r in rows:
        for kk in ("mean_wrong", "mean_cost"):
            ck(abs(pub[r["arm"]][kk] - r[kk]) < 1e-12, f"selection candidate {r['arm']} {kk}")
    eligible = [r for r in rows if r["mean_cost"] <= COST_MULT * 36.0]
    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
        pubk = serialization.load_pem_public_key((b / "E375_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
            {"E375_MANIFEST.json", "E375_SIGNED_BODY.json", "E375_TAMPER_RESULTS.json",
             "E375_VERIFICATION_RESULTS.json", "MANIFEST.json", "MERKLE_ROOT.txt",
             "PUBLICATION.json", "E375_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]))
