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

Recomputes every reported quantity from the raw per-instance latency tables:
certificate size m, R = 256 - m, cycle = ceil(R/S), the exhaustive one-row table,
the two-row histogram, the hidden-permutation expectation, the i.i.d. lease probability,
the 8-round frontier cost, H1-H6 and the pooled verdict. It also checks the row chain,
the salt commitments against the preregistration, 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()


def main(d):
    b = Path(d)
    rep = json.loads((b / "E358_RUN_REPORT.json").read_text())
    pre = json.loads((b / "E358_PREREGISTRATION.json").read_text())
    man = json.loads((b / "E358_MANIFEST.json").read_text())
    freeze = json.loads((b / "E358_PREREGISTRATION_FREEZE.json").read_text())
    salts = json.loads((b / "E358_SALT_REVEALED.json").read_text())

    ck(rep["schema"] == "cain42.e358.run.v1", "schema")
    ck(rep["evolution"] == "E358", "evolution")
    ck(rep["model_calls"] == 0, "zero model calls")
    ck(rep["api_spend_usd"] == 0.0, "zero API spend")
    ck(sha((b / "E358_PREREGISTRATION.json").read_bytes()) == freeze["preregistration_sha256"], "prereg freeze hash")
    ck(freeze["schema"] == "cain42.e358.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")

    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"]
        m = x["m"]
        ck(m == len(x["cert_rows"]), f"{tag} m == len(cert_rows)")
        ck(len(set(x["cert_rows"])) == m, f"{tag} cert rows distinct")
        ck(x["R"] == 256 - m, f"{tag} R == 256 - m")
        ck(x["sweep"] == 32, f"{tag} sweep 32")
        cyc = math.ceil(x["R"] / x["sweep"])
        ck(x["cycle_rounds"] == cyc, f"{tag} cycle")
        lat = x["single_latency"]
        ck(len(lat) == 256, f"{tag} 256 single latencies")
        cs = set(x["cert_rows"])
        ck(sum(1 for i, v in enumerate(lat) if i in cs and v == 1) == m, f"{tag} cert rows caught in round 1")
        ck(sum(1 for v in lat if v == 1) >= m, f"{tag} round 1 includes cert")
        ck(max(lat) == x["single_max"] == cyc, f"{tag} single max == cycle")
        ck(abs(sum(lat) / 256 - x["single_mean"]) < 1e-9, f"{tag} single mean")
        ck(x["strategic_worst"] == max(lat), f"{tag} strategic worst")
        ck(x["pair_max"] == cyc or x["pair_max"] == max(1, math.ceil((x["R"] - 1) / x["sweep"])),
           f"{tag} pair max bound")
        ck(sum(x["pair_hist"]) == 256 * 255 // 2, f"{tag} pair histogram total")
        ck(x["pair_max"] == len(x["pair_hist"]), f"{tag} pair hist length")
        ck(abs(sum((i + 1) * c for i, c in enumerate(x["pair_hist"])) / (256 * 255 // 2) - x["pair_mean"]) < 1e-9,
           f"{tag} pair mean")
        hmean = sum(p // x["sweep"] + 1 for p in range(x["R"])) / x["R"]
        ck(abs(hmean - x["hidden_mean_latency"]) < 1e-9, f"{tag} hidden mean")
        lease = 1 - (1 - x["sweep"] / x["R"]) ** cyc
        ck(abs(lease - x["lease_prob_at_cycle"]) < 1e-12, f"{tag} lease probability")
        ck(0.0 <= x["lease_mc_at_cycle"] <= 1.0, f"{tag} lease mc range")
        f8 = x["frontier"]["8"]
        ck(f8["sweep"] == math.ceil(x["R"] / 8), f"{tag} frontier sweep at 8")
        ck(f8["cost"] == m + f8["sweep"], f"{tag} frontier cost at 8")
        ck(abs(f8["ratio"] - f8["cost"] / 256) < 1e-12, f"{tag} frontier ratio at 8")
        ck(x["frontier_cost_at_8"] == f8["cost"], f"{tag} frontier cost carried")
        ck(x["class_sound"] == (x["covered_wrong"] == x["n_wrong_rules"]), f"{tag} class sound")
        ck(x["in_class_round1"] == x["class_sound"], f"{tag} in class round 1")

    # chain over instances
    prev = "0" * 64
    ok_chain = True
    for i, row in enumerate(rep["chain"]):
        base = {k: v for k, v in insts[i].items()}
        hh = sha((prev + sha(canon(base))).encode())
        if row["hash"] != hh or row["prev"] != prev or row["i"] != i:
            ok_chain = False
        prev = hh
    ck(ok_chain, "instance chain")
    ck(len(rep["chain"]) == 24, "chain length")

    # hypotheses recomputed
    prim = [x for x in insts if x["salt"] == "primary"]
    repl = [x for x in insts if x["salt"] == "replication"]

    def ev(group):
        n = len(group)
        a = sum(1 for x in group if x["class_sound"] and x["in_class_round1"])
        b = sum(1 for x in group if x["single_max"] <= x["cycle_rounds"] and x["pair_max"] <= x["cycle_rounds"])
        c = sum(1 for x in group if x["lease_prob_at_cycle"] <= 0.75)
        d = sum(1 for x in group if x["hidden_mean_latency"] <= 0.60 * x["strategic_worst"])
        e = sum(1 for x in group if x["frontier_ratio_at_8"] <= 0.30)
        return {"H1": a == n, "H2": b == n, "H3": c == n, "H4": d == n, "H5": e == n, "counts": (a, b, c, d, e, n)}

    p = ev(prim)
    r = ev(repl)
    ck(p["H1"], "H1 primary")
    ck(p["H2"], "H2 primary")
    ck(p["H3"], "H3 primary")
    ck(p["H4"], "H4 primary")
    ck(p["H5"], "H5 primary")
    ck(all(r[k] for k in ("H1", "H2", "H3", "H4", "H5")), "H6 replication")
    for k in ("H1_in_class_round1", "H2_single_row_guarantee", "H3_rotation_beats_lease",
              "H4_hidden_permutation_latency", "H5_cost_latency_frontier", "H6_replication"):
        ck(rep["hypotheses"][k]["verdict"] == "SUPPORTED", f"reported {k}")
    ck(rep["hypotheses"]["H7_external_review"]["verdict"] == "BLOCKED", "H7 blocked")
    ck(rep["verdict"] == "TWO_LAYER_DRIFT_DEFENCE_SUPPORTED", "verdict")
    ck(rep["replication_verdict"] == ("SUPPORTED" if all(r[k] for k in ("H1", "H2", "H3", "H4", "H5")) else "NOT_SUPPORTED"),
       "replication verdict")

    # summaries
    allg = insts
    ck(abs(rep["summaries"]["all"]["mean_m"] - sum(x["m"] for x in allg) / 24) < 1e-9, "summary mean m")
    ck(rep["summaries"]["all"]["class_sound"] == 24, "summary class sound")
    ck(rep["summaries"]["all"]["single_guarantee"] == 24, "summary single guarantee")
    ck(rep["summaries"]["all"]["pair_guarantee"] == 24, "summary pair guarantee")
    ck(rep["summaries"]["all"]["lease_max"] <= 0.75, "summary lease max")
    ck(rep["summaries"]["all"]["frontier_ratio_at_8_max"] <= 0.30, "summary frontier max")

    # manifest signature
    try:
        from cryptography.hazmat.primitives import serialization
        from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
        body = {k: v for k, v in man.items() if k != "signature"}
        pub = serialization.load_pem_public_key((b / "E358_PUBKEY.pem").read_bytes())
        pub.verify(bytes.fromhex(man["signature"]), canon(body))
        ck(True, "manifest signature")
    except Exception as e:  # pragma: no cover
        ck(False, "manifest signature", str(e))

    files = sorted(p for p in b.rglob("*") if p.is_file() and p.name not in
                   {"E358_MANIFEST.json", "E358_SIGNED_BODY.json", "E358_VERIFICATION_RESULTS.json",
                    "E358_TAMPER_RESULTS.json", "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json",
                    "E358_OMEGA_SEAL.json"} and "__pycache__" not in p.parts)
    leaves = sorted(sha(p.read_bytes()) for p in files)
    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 root")
    ck(not any(p.suffix == ".py" and "verify" not in p.name and "tamper" not in p.name for p in files),
       "no engine source in bundle")
    ck(any(p.name == "verify_e358_offline.py" for p in files), "verifier shipped")

    print(f"E358 offline verification: {CHECKS[0] - len(FAILS)}/{CHECKS[0]} checks passed")
    for f in FAILS[:20]:
        print("FAIL:", f)
    return 0 if not FAILS else 1


if __name__ == "__main__":
    sys.exit(main(sys.argv[1] if len(sys.argv) > 1 else "."))
