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

Recomputes every reported quantity from the published per-instance latency tables and schedules:

  R = 256 - m,  L = ceil(R / S)
  per arm: timing_worst = max(max_by_t), timing_mean = mean(mean_by_t), realised <= analytic bound
  bounds: L for a time-invariant order, 2L-1 for a per-cycle randomised order, none for i.i.d.
  the i.i.d. analytic tail (1 - S/R)^(2L)
  every hypothesis H1-H8 on the primary and replication salts, the pooled verdict
  the development-only schedule selection and H8
  the v1 near-miss is preserved (its report is present and its verdict was NOT_SUPPORTED)
  the row chain, the salt commitments (and that they differ from v1), the manifest signature,
  and that no engine source is present in the public bundle.
"""
from __future__ import annotations

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

FAILS = []
CHECKS = [0]


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()


ARMS5 = ("PUBLIC_FIXED", "SECRET_FIXED", "SECRET_PER_CYCLE", "ROTATED_FIXED", "IID")
ARMS = ARMS5 + ("FULL",)
SWEEP = 32
COST_CAP = 0.15


def main(d):
    b = Path(d)
    rep = json.loads((b / "E364_RUN_REPORT.json").read_text())
    pre = json.loads((b / "E364_PREREGISTRATION.json").read_text())
    man = json.loads((b / "E364_MANIFEST.json").read_text())
    freeze = json.loads((b / "E364_PREREGISTRATION_FREEZE.json").read_text())
    salts = json.loads((b / "E364_SALT_REVEALED.json").read_text())
    dev = json.loads((b / "E364_DEVIATIONS.json").read_text())
    v1 = json.loads((b / "E364_RUN_REPORT.v1.json").read_text())
    v1_pre = json.loads((b / "E364_PREREGISTRATION.v1.json").read_text())

    ck(rep["schema"] == "cain42.e364.run.v1", "schema")
    ck(rep["evolution"] == "E364", "evolution")
    ck(rep["model_calls"] == 0, "zero model calls")
    ck(rep["api_spend_usd"] == 0.0, "zero API spend")
    ck(rep["weights_changed"] == 0, "zero weights changed")
    ck(sha((b / "E364_PREREGISTRATION.json").read_bytes()) == freeze["preregistration_sha256"], "prereg freeze hash")
    ck(freeze["schema"] == "cain42.e364.freeze.v2", "freeze schema v2")
    ck(pre.get("version") == 2, "prereg v2")
    ck(pre.get("supersedes") == "E364_PREREGISTRATION.v1.json", "supersedes v1")
    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("fresh salts" in dev["deviations"][0]["correction"], "D1 fresh salts")
    # v1 near-miss preserved and was a genuine miss
    ck(v1["verdict"] == "NOT_SUPPORTED", "v1 verdict preserved NOT_SUPPORTED", v1["verdict"])
    ck(v1["hypotheses"]["H6_replication"]["verdict"] == "NOT_SUPPORTED", "v1 H6 miss preserved")
    ck(v1["replication_hypotheses"]["H2_randomised_per_cycle_doubles"]["verdict"] == "NOT_SUPPORTED",
       "v1 replication H2 miss preserved")
    ck(v1["replication_verdict"] == "NOT_SUPPORTED", "v1 replication verdict preserved")

    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")
    ck(set(rep["selection"]["candidates"][0]) == {"arm", "mean_timing_worst", "mean_pre_mean", "cost_ratio"}, "selection row shape")

    for x in insts:
        tag = x["id"]
        ck(x["R"] == 256 - x["m"], f"{tag} R", f"{x['R']} vs {256-x['m']}")
        ck(x["L"] == math.ceil(x["R"] / SWEEP), f"{tag} L")
        ck(len(set(x["cert_rows"])) == x["m"], f"{tag} cert distinct")
        ck(all(0 <= r < 256 for r in x["cert_rows"]), f"{tag} cert range")
        ck(x["class_sound"] is True, f"{tag} class sound")
        ck(set(x["arms"]) == set(ARMS), f"{tag} arms")
        L = x["L"]
        for arm in ARMS:
            a = x["arms"][arm]
            ck(a["timing_worst"] == max(a["max_by_t"]), f"{tag} {arm} worst==max(max_by_t)")
            ck(abs(a["timing_mean"] - sum(a["mean_by_t"]) / len(a["mean_by_t"])) < 1e-12, f"{tag} {arm} mean")
            if arm in ("PUBLIC_FIXED", "SECRET_FIXED"):
                ck(a["timing_bound"] == L, f"{tag} {arm} bound L")
            elif arm in ("SECRET_PER_CYCLE", "ROTATED_FIXED"):
                ck(a["timing_bound"] == 2 * L - 1, f"{tag} {arm} bound 2L-1")
            elif arm == "IID":
                ck(a["timing_bound"] is None, f"{tag} IID no bound")
            else:
                ck(a["timing_bound"] == 1, f"{tag} FULL bound 1")
            if a["timing_bound"] is not None:
                ck(a["timing_worst"] <= a["timing_bound"], f"{tag} {arm} realised <= bound",
                   f"{a['timing_worst']} > {a['timing_bound']}")
            if arm in ARMS5 and arm != "IID":
                ck(abs(a["cost_rows_per_round"] - (SWEEP + x["m"] / L)) < 1e-9, f"{tag} {arm} cost")
                ck(a["cost_ratio"] <= COST_CAP + 1e-12, f"{tag} {arm} cost cap")
            if arm == "PUBLIC_FIXED":
                ck(a["pre_mean"] == L, f"{tag} public pre_mean L")
            if arm == "SECRET_FIXED":
                ck(a["pre_mean"] == a["pre_uniform_mean"], f"{tag} secret pre_mean uniform")
                ck(a["pre_mean"] < 0.60 * x["arms"]["PUBLIC_FIXED"]["pre_mean"], f"{tag} secrecy gain")
            if arm == "IID":
                p = SWEEP / x["R"]
                ck(abs(a["iid_p"] - p) < 1e-15, f"{tag} iid p")
                ck(abs(a["iid_p_gt_2L"] - (1 - p) ** (2 * L)) < 1e-12, f"{tag} iid tail")
        ck(x["arms"]["SECRET_PER_CYCLE"]["timing_worst"] == 2 * L - 1, f"{tag} percycle realises 2L-1")
        ck(x["arms"]["ROTATED_FIXED"]["timing_worst"] <= 2 * L - 1, f"{tag} rotated <= 2L-1")

    # summaries
    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_L": sum(x["L"] for x in lst) / n,
            "class_sound": sum(1 for x in lst if x["class_sound"]),
            "fixed_bound_exact": sum(1 for x in lst if x["arms"]["PUBLIC_FIXED"]["timing_worst"] == x["L"]
                                     and x["arms"]["SECRET_FIXED"]["timing_worst"] == x["L"]
                                     and x["arms"]["PUBLIC_FIXED"]["timing_bound"] == x["L"]
                                     and x["arms"]["SECRET_FIXED"]["timing_bound"] == x["L"]),
            "random_bound_doubled": sum(1 for x in lst if x["arms"]["SECRET_PER_CYCLE"]["timing_bound"] == 2 * x["L"] - 1
                                        and x["arms"]["ROTATED_FIXED"]["timing_bound"] == 2 * x["L"] - 1),
            "percycle_realised_bound": sum(1 for x in lst if x["arms"]["SECRET_PER_CYCLE"]["timing_worst"] == 2 * x["L"] - 1),
            "iid_tail": sum(1 for x in lst if x["arms"]["IID"]["iid_p_gt_2L"] >= 0.01),
            "iid_worst_gt_2L": sum(1 for x in lst if x["arms"]["IID"]["timing_worst"] > 2 * x["L"]),
            "secrecy_gain": sum(1 for x in lst if x["arms"]["SECRET_FIXED"]["pre_mean"] <= 0.60 * x["arms"]["PUBLIC_FIXED"]["pre_mean"]),
        }
    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():
            ck(got[k] == v, f"summary {label} {k}", f"{got[k]} vs {v}")
        for key in ("timing_worst", "timing_mean", "pre_mean", "cost_ratio"):
            for arm in ARMS:
                exp = sum(x["arms"][arm][key] for x in lst) / len(lst)
                ck(abs(got[key][arm] - exp) < 1e-12, f"summary {label} {key} {arm}",
                   f"{got[key][arm]} vs {exp}")

    # hypotheses recomputed exactly
    def ev(lst):
        n = len(lst)
        a = {x["id"]: x for x in lst}

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

        h1 = sum(1 for x in lst if g(x, "PUBLIC_FIXED", "timing_worst") == x["L"]
                 and g(x, "SECRET_FIXED", "timing_worst") == x["L"]
                 and g(x, "PUBLIC_FIXED", "timing_bound") == x["L"]
                 and g(x, "SECRET_FIXED", "timing_bound") == x["L"])
        h2 = sum(1 for x in lst if g(x, "SECRET_PER_CYCLE", "timing_bound") == 2 * x["L"] - 1
                 and g(x, "ROTATED_FIXED", "timing_bound") == 2 * x["L"] - 1)
        h2b = sum(1 for x in lst if g(x, "SECRET_PER_CYCLE", "timing_worst") == 2 * x["L"] - 1)
        h3 = sum(1 for x in lst if g(x, "SECRET_FIXED", "pre_mean") <= 0.60 * g(x, "PUBLIC_FIXED", "pre_mean"))
        h4a = sum(1 for x in lst if g(x, "IID", "iid_p_gt_2L") >= 0.01)
        h4b = sum(1 for x in lst if g(x, "IID", "timing_worst") > 2 * x["L"])
        h4c = sum(1 for x in lst if g(x, "IID", "timing_bound") is None)
        h5 = sum(1 for x in lst for arm in ARMS5 if g(x, arm, "cost_ratio") <= COST_CAP) / (5 * n)
        sel = rep["selection"]["selected"]
        h8a = sum(1 for x in lst if g(x, sel, "timing_worst") == min(g(x, y, "timing_worst") for y in ARMS5))
        h8b = sum(1 for x in lst if g(x, sel, "pre_mean") <= 0.75 * g(x, "PUBLIC_FIXED", "pre_mean"))
        return {
            "H1_fixed_cycle_bounds_timing": ("SUPPORTED" if h1 == n else "NOT_SUPPORTED", h1),
            "H2_randomised_per_cycle_doubles": ("SUPPORTED" if (h2 == n and h2b >= math.ceil(0.9 * n)) else "NOT_SUPPORTED", h2),
            "H3_secrecy_helps_precommitted_only": ("SUPPORTED" if h3 >= math.ceil(0.9 * n) else "NOT_SUPPORTED", h3),
            "H4_iid_has_no_bound": ("SUPPORTED" if (h4a == n and h4b >= math.ceil(0.9 * n) and h4c == n) else "NOT_SUPPORTED", h4c),
            "H5_cost_cap": ("SUPPORTED" if h5 == 1.0 else "NOT_SUPPORTED", h5),
            "H8_dev_selection": ("SUPPORTED" if (sel == "SECRET_FIXED" and h8a == n and h8b == n) else "NOT_SUPPORTED", h8a),
        }
    for label, lst in (("primary", prim), ("replication", repl)):
        want = ev(lst)
        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).items())
    rep_ok = all(v == "SUPPORTED" for k, (v, _) in ev(repl).items())
    want_verdict = "SCHEDULE_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")

    # development-only selection recomputed
    rows = []
    for a in ARMS:
        cr = sum(y["arms"][a]["cost_ratio"] for y in rep["dev_instances"]) / len(rep["dev_instances"])
        if a == "FULL" or cr > COST_CAP:
            continue
        tw = sum(y["arms"][a]["timing_worst"] for y in rep["dev_instances"]) / len(rep["dev_instances"])
        pm = sum(y["arms"][a]["pre_mean"] for y in rep["dev_instances"]) / len(rep["dev_instances"])
        rows.append({"arm": a, "mean_timing_worst": tw, "mean_pre_mean": pm, "cost_ratio": cr})
    rows.sort(key=lambda r: (round(r["mean_timing_worst"], 9), round(r["mean_pre_mean"], 9),
                             round(r["cost_ratio"], 9), ARMS.index(r["arm"])))
    ck(rows[0]["arm"] == rep["selection"]["selected"], "selection recomputed", f"{rows[0]['arm']} vs {rep['selection']['selected']}")
    ck(rep["selection"]["uses_dev_only"] is True, "selection uses dev only")
    ck(all(abs(x["mean_timing_worst"] - y["mean_timing_worst"]) < 1e-12 for x, y in zip(rows, rep["selection"]["candidates"])), "selection candidates match")

    # row chain
    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

    # manifest + signature + no engine source
    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 / "E364_PUBKEY.pem").read_bytes())
        pub.verify(bytes.fromhex(man["signature"]), canon(body))
        sig_ok = True
    except Exception as e:  # noqa: BLE001
        sig_ok = False
        ck(False, "manifest signature", str(e)[:120])
    if sig_ok:
        ck(True, "manifest signature")
    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")
    ck(man["headline"]["v1_near_miss"] == "NOT_SUPPORTED", "headline v1 near-miss")
    disk = {str(p.relative_to(b)) for p in b.rglob("*") if p.is_file()
            and str(p.relative_to(b)) not in
            {"E364_MANIFEST.json", "E364_SIGNED_BODY.json", "E364_TAMPER_RESULTS.json",
             "E364_VERIFICATION_RESULTS.json", "MANIFEST.json", "MERKLE_ROOT.txt",
             "PUBLICATION.json", "E364_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")
    ck(not any(p.name == "run.py" for p in b.rglob("cain/*")), "no cain package")

    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]))
