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

Recomputes every cell from k, the budget and the window:
  uniform gap = ceil(k/32); skew gap = ceil((k-k/8)/(32-k/8)); random worst over 200 seeds
  per adversary (unrestricted/top-only), window and arm: latency, caught, wrong, cost
then H1-H5/H8 on primary and replication, the pooled verdict, the dev-only selection, the row chain,
the salt commitments, the manifest signature, no unlisted files and no engine source.
"""
from __future__ import annotations

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

FAILS = []
CHECKS = [0]
K_VALUES = (64, 128)
WINDOWS = (("W1", 1), ("W5", 5), ("PERSISTENT", None))
ARMS = ("UNIFORM", "SKEW", "RANDOM", "FULL")
ADVERSARIES = ("UNRESTRICTED", "TOP_ONLY")
BUDGET = 32
USES = 60
RANDOM_SEEDS = 200


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 h(*parts):
    return int.from_bytes(hashlib.sha256("|".join(map(str, parts)).encode()).digest()[:8], "big")


def random_worst(k, s, uses, seed):
    rng = random.Random(seed)
    last = {r: -1 for r in range(k)}
    worst = 0
    for t in range(uses):
        for r in rng.sample(range(k), s):
            if last[r] >= 0:
                worst = max(worst, t - last[r])
            last[r] = t
    return worst


def wrong_for_gap(gap, w, uses=USES):
    if gap >= uses:
        return uses, False
    if w is None:
        return gap, True
    if gap >= w:
        return w, False
    return gap, True


def main(d):
    b = Path(d)
    rep = json.loads((b / "E376M_RUN_REPORT.json").read_text())
    pre = json.loads((b / "E376M_PREREGISTRATION.json").read_text())
    man = json.loads((b / "E376M_MANIFEST.json").read_text())
    freeze = json.loads((b / "E376M_PREREGISTRATION_FREEZE.json").read_text())
    salts = json.loads((b / "E376M_SALT_REVEALED.json").read_text())
    dev = json.loads((b / "E376M_DEVIATIONS.json").read_text())

    ck(rep["schema"] == "cain42.e376m.run.v1", "schema")
    ck(rep["evolution"] == "E376-M", "evolution")
    ck(rep["model_calls"] == 0 and rep["api_spend_usd"] == 0.0 and rep["weights_changed"] == 0, "zero resources")
    ck(sha((b / "E376M_PREREGISTRATION.json").read_bytes()) == freeze["preregistration_sha256"], "prereg freeze hash")
    ck(freeze["schema"] == "cain42.e376m.freeze.v1", "freeze schema")
    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")
    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)
            cell = x["cells"][key]
            p = k // 8
            c = math.ceil((k - p) / (BUDGET - p))
            ug = math.ceil(k / BUDGET)
            ck(cell["k"] == k and cell["p_top"] == p and cell["budget"] == BUDGET, f"{tag} k={k} meta")
            ck(cell["uniform_gap"] == ug and cell["skew_gap"] == c, f"{tag} k={k} gaps")
            rws = sorted(random_worst(k, BUDGET, USES, h("E376M-random", k, seed)) for seed in range(RANDOM_SEEDS))
            ck(abs(cell["random_worst_mean"] - sum(rws) / len(rws)) < 1e-9, f"{tag} k={k} random mean")
            ck(abs(cell["random_worst_p05"] - rws[int(0.05 * len(rws))]) < 1e-9, f"{tag} k={k} random p05")
            for adv in ADVERSARIES:
                ck(set(cell["adversaries"][adv]) == {w for w, _ in WINDOWS}, f"{tag} k={k} {adv} windows")
                for name, w in WINDOWS:
                    want = {
                        "UNIFORM": (ug, BUDGET),
                        "SKEW": (1 if adv == "TOP_ONLY" else c, BUDGET),
                        "RANDOM": (max(1, int(round(cell["random_worst_mean"]))), BUDGET),
                        "FULL": (1, 256),
                    }
                    ck(set(cell["adversaries"][adv][name]) == set(ARMS), f"{tag} k={k} {adv} {name} arms")
                    for arm in ARMS:
                        gap, cost = want[arm]
                        wr, ct = wrong_for_gap(gap, w)
                        got = cell["adversaries"][adv][name][arm]
                        ck(got["latency"] == gap and got["cost"] == cost
                           and got["caught_rate"] == (1.0 if ct else 0.0)
                           and got["mean_wrong"] == float(wr), f"{tag} k={k} {adv} {name} {arm}")

    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] = {"meta": {"uniform_gap": lst[0]["cells"][key]["uniform_gap"],
                                 "skew_gap": lst[0]["cells"][key]["skew_gap"],
                                 "random_worst_mean": sum(x["cells"][key]["random_worst_mean"] for x in lst) / n,
                                 "random_worst_p05": sum(x["cells"][key]["random_worst_p05"] for x in lst) / n}}
            for adv in ADVERSARIES:
                out[key][adv] = {name: {a: {"caught_rate": sum(x["cells"][key]["adversaries"][adv][name][a]["caught_rate"] for x in lst) / n,
                                             "mean_wrong": sum(x["cells"][key]["adversaries"][adv][name][a]["mean_wrong"] for x in lst) / n,
                                             "latency": sum(x["cells"][key]["adversaries"][adv][name][a]["latency"] for x in lst) / n,
                                             "cost": sum(x["cells"][key]["adversaries"][adv][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 mk in ("uniform_gap", "random_worst_mean", "random_worst_p05"):
                ck(abs(got[key]["meta"][mk] - want[key]["meta"][mk]) < 1e-9, f"summary {label} {key} meta {mk}")
            for adv in ADVERSARIES:
                for name, _w in WINDOWS:
                    for a in ARMS:
                        for kk in ("caught_rate", "mean_wrong", "latency", "cost"):
                            ck(abs(got[key][adv][name][a][kk] - want[key][adv][name][a][kk]) < 1e-12, f"summary {label} {key} {adv} {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, adv, win, arm, key):
            return x["cells"][str(k)]["adversaries"][adv][win][arm][key]
        h1 = sum(1 for x in lst if all(g(x, k, "UNRESTRICTED", "PERSISTENT", "UNIFORM", "latency") == x["cells"][str(k)]["uniform_gap"] for k in K_VALUES))
        h2 = sum(1 for x in lst if all(g(x, k, "UNRESTRICTED", "PERSISTENT", "SKEW", "latency") == x["cells"][str(k)]["skew_gap"]
                                       and x["cells"][str(k)]["skew_gap"] > x["cells"][str(k)]["uniform_gap"] for k in K_VALUES))
        h3 = sum(1 for x in lst if all(g(x, k, "TOP_ONLY", "PERSISTENT", "SKEW", "latency") == 1
                                       and g(x, k, "TOP_ONLY", "PERSISTENT", "UNIFORM", "latency") > 1 for k in K_VALUES))
        h4 = sum(1 for x in lst if all(g(x, k, "UNRESTRICTED", "PERSISTENT", "RANDOM", "latency") >= 2 * x["cells"][str(k)]["uniform_gap"] for k in K_VALUES))
        h5 = sum(1 for x in lst if all(g(x, k, "UNRESTRICTED", "W1", a, "cost") == BUDGET for k in K_VALUES for a in ("UNIFORM", "SKEW", "RANDOM"))
                 and all(g(x, k, "UNRESTRICTED", "W1", "FULL", "cost") == 256 for k in K_VALUES))
        h8a = sum(1 for x in lst if all(g(x, k, "UNRESTRICTED", "PERSISTENT", sel, "latency") <= min(
            g(x, k, "UNRESTRICTED", "PERSISTENT", a, "latency") for a in ARMS if g(x, k, "UNRESTRICTED", "W1", a, "cost") <= BUDGET) for k in K_VALUES))
        h8b = sum(1 for x in lst if all(g(x, k, "UNRESTRICTED", "W1", sel, "cost") <= BUDGET for k in K_VALUES))
        return {
            "H1_uniform_bound": ("SUPPORTED" if h1 == n else "NOT_SUPPORTED", h1),
            "H2_skew_is_exploitable": ("SUPPORTED" if h2 == n else "NOT_SUPPORTED", h2),
            "H3_skew_wins_when_restricted": ("SUPPORTED" if h3 == n else "NOT_SUPPORTED", h3),
            "H4_random_has_no_bound": ("SUPPORTED" if h4 >= math.ceil(0.9 * n) else "NOT_SUPPORTED", h4),
            "H5_cost_equal": ("SUPPORTED" if h5 == n else "NOT_SUPPORTED", h5),
            "H8_dev_selection": ("SUPPORTED" if (sel == "UNIFORM" 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"] == ("MINIMAX_ROW_ALLOCATION_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:
        lat = sum(y["cells"][str(k)]["adversaries"]["UNRESTRICTED"]["PERSISTENT"][a]["latency"] for y in rep["dev_instances"] for k in K_VALUES) / (len(K_VALUES) * len(rep["dev_instances"]))
        cost = sum(y["cells"][str(k)]["adversaries"]["UNRESTRICTED"]["W1"][a]["cost"] for y in rep["dev_instances"] for k in K_VALUES) / (len(K_VALUES) * len(rep["dev_instances"]))
        rows.append({"arm": a, "mean_latency": lat, "mean_cost": cost})
    for r in rows:
        for kk in ("mean_latency", "mean_cost"):
            ck(abs(rep["selection"]["candidates"][ARMS.index(r["arm"])][kk] - r[kk]) < 1e-12, f"selection candidate {r['arm']} {kk}")
    eligible = [r for r in rows if r["mean_cost"] <= BUDGET]
    eligible.sort(key=lambda r: (round(r["mean_latency"], 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 / "E376M_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
            {"E376M_MANIFEST.json", "E376M_SIGNED_BODY.json", "E376M_TAMPER_RESULTS.json",
             "E376M_VERIFICATION_RESULTS.json", "MANIFEST.json", "MERKLE_ROOT.txt",
             "PUBLICATION.json", "E376M_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]))
