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

Recomputes from the published per-instance rows:
  R = 256 - m,  K0 = ceil(R / B),  horizon = 6 K0
  per arm: cost = mean(round_sizes), bound = max(max_by_t), mean = mean(mean_by_t),
           flat_at_cost = ceil(R / cost), schedule-spec checks
  every hypothesis H1-H5/H8 on primary and replication, the pooled verdict, the dev-only selection
  the row chain, the salt commitments (and that they differ from v1), the manifest signature,
  no unlisted files and no engine source. v1's rows are preserved and must match v2's bounds.
"""
from __future__ import annotations

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

FAILS = []
CHECKS = [0]
ARMS = ("FLAT", "BURST_SAME_K", "ADAPT_2X", "RANDOM_K", "FULL")
BUDGET = 32
COST_TOL = 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 main(d):
    b = Path(d)
    rep = json.loads((b / "E369_RUN_REPORT.json").read_text())
    pre = json.loads((b / "E369_PREREGISTRATION.json").read_text())
    man = json.loads((b / "E369_MANIFEST.json").read_text())
    freeze = json.loads((b / "E369_PREREGISTRATION_FREEZE.json").read_text())
    salts = json.loads((b / "E369_SALT_REVEALED.json").read_text())
    dev = json.loads((b / "E369_DEVIATIONS.json").read_text())
    v1 = json.loads((b / "E369_RUN_REPORT.v1.json").read_text())
    v1_pre = json.loads((b / "E369_PREREGISTRATION.v1.json").read_text())

    ck(rep["schema"] == "cain42.e369.run.v1", "schema")
    ck(rep["evolution"] == "E369", "evolution")
    ck(rep["model_calls"] == 0 and rep["api_spend_usd"] == 0.0 and rep["weights_changed"] == 0, "zero resources")
    ck(sha((b / "E369_PREREGISTRATION.json").read_bytes()) == freeze["preregistration_sha256"], "prereg freeze hash")
    ck(freeze["schema"] == "cain42.e369.freeze.v2", "freeze schema v2")
    ck(pre.get("version") == 2 and pre.get("supersedes") == "E369_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("reporting" in dev["deviations"][0]["kind"], "D1 reporting-only")
    # v1 preserved; this was a reporting change, so the bounds must be identical
    ck(v1["verdict"] == "FLAT_BUDGET_TIMING_LAW_SUPPORTED", "v1 verdict preserved")
    ck(v1["summaries"]["all"]["bound"] == rep["summaries"]["all"]["bound"], "v1/v2 bounds identical")

    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, K0, H = x["R"], x["K0"], x["horizon"]
        ck(R == 256 - x["m"], f"{tag} R")
        ck(K0 == math.ceil(R / BUDGET), f"{tag} K0")
        ck(H == 6 * K0, f"{tag} horizon")
        ck(x["class_sound"] is True, f"{tag} class sound")
        ck(set(x["arms"]) == set(ARMS), f"{tag} arms")
        for arm in ARMS:
            a = x["arms"][arm]
            ck(len(a["round_sizes"]) == H, f"{tag} {arm} round_sizes len")
            ck(len(a["max_by_t"]) == H and len(a["mean_by_t"]) == H, f"{tag} {arm} table len")
            cost = sum(a["round_sizes"]) / H
            ck(abs(a["cost"] - cost) < 1e-9, f"{tag} {arm} cost", f"{a['cost']} vs {cost}")
            ck(abs(a["cost_ratio"] - cost / 256) < 1e-12, f"{tag} {arm} cost ratio")
            ck(a["flat_at_cost"] == math.ceil(R / cost), f"{tag} {arm} flat_at_cost")
            ck(a["bound"] == max(a["max_by_t"]), f"{tag} {arm} bound")
            ck(abs(a["mean"] - sum(a["mean_by_t"]) / H) < 1e-12, f"{tag} {arm} mean")
            if arm in ("FLAT", "BURST_SAME_K"):
                ck(a["schedule"]["K"] == K0, f"{tag} {arm} spec K")
                ck(a["bound"] == K0, f"{tag} {arm} bound==K0")
            if arm in ("ADAPT_2X", "RANDOM_K"):
                ck(a["schedule"]["K_fast"] == max(1, math.ceil(R / (2 * BUDGET))), f"{tag} {arm} K_fast")
                ck(a["schedule"]["K_slow"] == 2 * K0, f"{tag} {arm} K_slow")
            if arm == "ADAPT_2X":
                ck(a["bound"] >= 1.8 * K0, f"{tag} ADAPT bound >=1.8K0")
                ck(a["bound"] >= a["flat_at_cost"], f"{tag} ADAPT never beats flat at equal cost")
            if arm == "RANDOM_K":
                ck(a["bound"] >= 1.5 * K0, f"{tag} RANDOM bound >=1.5K0")
            if arm == "FULL":
                ck(a["bound"] == 1, f"{tag} FULL bound 1")

    def sm(lst):
        n = len(lst)
        return {
            "instances": n,
            "mean_m": sum(x["m"] for x in lst) / n,
            "mean_R": sum(x["R"] for x in lst) / n,
            "mean_K0": sum(x["K0"] for x in lst) / n,
            "class_sound": sum(1 for x in lst if x["class_sound"]),
            "bound": {a: sum(x["arms"][a]["bound"] for x in lst) / n for a in ARMS},
            "mean": {a: sum(x["arms"][a]["mean"] for x in lst) / n for a in ARMS},
            "cost": {a: sum(x["arms"][a]["cost"] for x in lst) / n for a in ARMS},
            "flat_exact": sum(1 for x in lst if x["arms"]["FLAT"]["bound"] == x["K0"]),
            "burst_exact": sum(1 for x in lst if x["arms"]["BURST_SAME_K"]["bound"] == x["K0"]),
            "adapt_double": sum(1 for x in lst if x["arms"]["ADAPT_2X"]["bound"] >= 1.8 * x["K0"]),
            "adapt_not_better": sum(1 for x in lst if x["arms"]["ADAPT_2X"]["bound"] >= x["arms"]["ADAPT_2X"]["flat_at_cost"]),
            "random_worse": sum(1 for x in lst if x["arms"]["RANDOM_K"]["bound"] >= 1.5 * x["K0"]),
        }
    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:
                    ck(abs(got[k][arm] - v[arm]) < 1e-12, f"summary {label} {k} {arm}")
            else:
                ck(got[k] == v, f"summary {label} {k}", f"{got[k]} vs {v}")

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

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

        h1 = sum(1 for x in lst if a(x, "FLAT", "bound") == x["K0"])
        h2 = sum(1 for x in lst if a(x, "ADAPT_2X", "bound") >= 1.8 * x["K0"])
        h3 = sum(1 for x in lst if a(x, "ADAPT_2X", "bound") >= a(x, "ADAPT_2X", "flat_at_cost"))
        h4 = sum(1 for x in lst if a(x, "RANDOM_K", "bound") >= 1.5 * x["K0"])
        h5 = sum(1 for x in lst if a(x, "BURST_SAME_K", "bound") == x["K0"])
        h8a = sum(1 for x in lst if a(x, sel, "bound") <= min(a(x, "ADAPT_2X", "bound"), a(x, "RANDOM_K", "bound")))
        h8b = sum(1 for x in lst if a(x, sel, "cost") <= COST_TOL * max(a(x, "ADAPT_2X", "cost"), a(x, "RANDOM_K", "cost")))
        return {
            "H1_flat_bound_is_the_period": ("SUPPORTED" if h1 == n else "NOT_SUPPORTED", h1),
            "H2_adaptive_doubles_the_bound": ("SUPPORTED" if h2 >= math.ceil(0.9 * n) else "NOT_SUPPORTED", h2),
            "H3_adaptive_never_beats_flat_at_equal_cost": ("SUPPORTED" if h3 == n else "NOT_SUPPORTED", h3),
            "H4_random_periods_are_worse": ("SUPPORTED" if h4 >= math.ceil(0.9 * n) else "NOT_SUPPORTED", h4),
            "H5_distribution_invariance": ("SUPPORTED" if h5 == n else "NOT_SUPPORTED", h5),
            "H8_dev_selection": ("SUPPORTED" if (sel == "FLAT" and h8a == n and h8b == n) else "NOT_SUPPORTED", h8a),
        }
    for label, lst in (("primary", prim), ("replication", repl)):
        want = ev(lst, rep["selection"]["selected"])
        for k, (v, _) in want.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())
    want_verdict = "FLAT_BUDGET_TIMING_LAW_SUPPORTED" if (ok and rep_ok) else "NOT_SUPPORTED"
    ck(rep["verdict"] == want_verdict, "pooled verdict", f"{rep['verdict']} vs {want_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:
        if a == "FULL":
            continue
        cost = sum(y["arms"][a]["cost"] for y in rep["dev_instances"]) / len(rep["dev_instances"])
        bound = sum(y["arms"][a]["bound"] for y in rep["dev_instances"]) / len(rep["dev_instances"])
        rows.append({"arm": a, "mean_bound": bound, "mean_cost": cost})
    eligible = [r for r in rows if r["mean_cost"] <= COST_TOL * BUDGET]
    eligible.sort(key=lambda r: (round(r["mean_bound"], 9), round(r["mean_cost"], 9), ARMS.index(r["arm"])))
    ck(eligible[0]["arm"] == rep["selection"]["selected"], "selection recomputed")
    ck(rep["selection"]["uses_dev_only"] is True, "selection dev only")

    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 root 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 / "E369_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
            {"E369_MANIFEST.json", "E369_SIGNED_BODY.json", "E369_TAMPER_RESULTS.json",
             "E369_VERIFICATION_RESULTS.json", "MANIFEST.json", "MERKLE_ROOT.txt",
             "PUBLICATION.json", "E369_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]))
