#!/usr/bin/env python3
"""Standalone E368-X verifier — stdlib only, imports no CAIN code."""
from __future__ import annotations

import hashlib, json, 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 / "E368X_RUN_REPORT.json").read_text())
    pre = json.loads((b / "E368X_PREREGISTRATION.json").read_text())
    man = json.loads((b / "E368X_MANIFEST.json").read_text())
    frz = json.loads((b / "E368X_PREREGISTRATION_FREEZE.json").read_text())
    salts = json.loads((b / "E368X_SALT_REVEALED.json").read_text())
    ck(rep["schema"] == "cain42.e368x.run.v1", "schema")
    ck(rep["evolution"] == "E368-X", "evolution")
    ck(rep["model_calls"] == 0 and rep["api_spend_usd"] == 0.0, "zero calls/spend")
    ck(sha((b / "E368X_PREREGISTRATION.json").read_bytes()) == frz["preregistration_sha256"], "prereg hash")
    ck(pre["salt_commitment_sha256"] == rep["salt_commitment_sha256"], "salt commitments")
    for s in ("primary", "replication"):
        ck(sha(bytes.fromhex(salts[s])) == pre["salt_commitment_sha256"][s], f"salt {s}")

    eps = rep["episodes"]
    ck(len(eps) == 24, "24 instances")
    for e in eps:
        tag = e["id"]
        r0 = int(e["r0_mask"], 16); f1 = r0 ^ (1 << e["r1"]); f2 = f1 ^ (1 << e["r2"])
        ck(f1 == int(e["f1_mask"], 16) and f2 == int(e["f2_mask"], 16), f"{tag} masks")
        ck(e["r1"] != e["r2"], f"{tag} distinct drifts")
        ck(e["r1"] not in e["cert_rows"] and e["r2"] not in e["cert_rows"], f"{tag} outside cert")
        ck(e["certifications"]["FULL_COMPLEMENT"]["rows"] == 255, f"{tag} full cost")
        ck(e["certifications"]["FULL_COMPLEMENT"]["accepted"] is True, f"{tag} full accepts")
        ck(e["certifications"]["BASE_CERT"]["rows"] == e["cert_out_size"], f"{tag} base cost")
        ck(e["certifications"]["BASE_CERT"]["accepted"] is True, f"{tag} base accepts")
        ck(e["certifications"]["SAMPLE_64"]["rows"] == 64, f"{tag} sample cost")
        p = e["policies"]
        ck(p["PERMANENT"]["wrong_uses"] == 50 and p["PERMANENT"]["detection_use"] is None, f"{tag} permanent")
        ck(p["LEASE_CERT"]["wrong_uses"] == 50 and p["LEASE_CERT"]["detection_use"] is None, f"{tag} cert blind")
        pos = e["full_perm"].index(e["r2"]); det = 10 + ((pos // 32 - 2) % 8)
        ck(p["LEASE_32"]["detection_use"] == det and p["LEASE_32"]["wrong_uses"] == det - 10, f"{tag} full lease")
        ck(p["LEASE_32"]["final_correct"] is True, f"{tag} full lease exact")
        ck(p["LEASE_COMPLEMENT"]["detection_use"] is None or 10 <= p["LEASE_COMPLEMENT"]["detection_use"] <= 17, f"{tag} comp range")
        ck(p["LEASE_COMPLEMENT"]["wrong_uses"] <= 7 and p["LEASE_COMPLEMENT"]["final_correct"] is True, f"{tag} comp lease")
        ck(p["FULL_EACH"]["wrong_uses"] == 0 and p["FULL_EACH"]["detection_use"] == 10, f"{tag} full each")
        ck(p["FULL_EACH"]["labels"] == 256 * 60, f"{tag} full labels")

    prev = "0" * 64; ok = True
    for i, row in enumerate(rep["chain"]):
        hh = sha((prev + sha(canon(eps[i]))).encode())
        if row["hash"] != hh or row["prev"] != prev or row["i"] != i:
            ok = False
        prev = hh
    ck(ok, "episode chain"); ck(len(rep["chain"]) == 24, "chain length")

    def ev(group):
        n = len(group)
        a = sum(1 for e in group if e["certifications"]["FULL_COMPLEMENT"]["accepted"]
                and e["certifications"]["FULL_COMPLEMENT"]["rows"] == 255 and e["policies"]["LEASE_32"]["final_correct"])
        b = sum(1 for e in group if e["policies"]["LEASE_CERT"]["wrong_uses"] == 50)
        c = sum(1 for e in group if e["policies"]["LEASE_32"]["wrong_uses"] <= 7)
        cm = sum(e["policies"]["LEASE_32"]["wrong_uses"] for e in group) / n
        d = sum(1 for e in group if e["policies"]["LEASE_COMPLEMENT"]["wrong_uses"] <= 7
                and e["policies"]["LEASE_COMPLEMENT"]["final_correct"])
        f = sum(1 for e in group if e["certifications"]["BASE_CERT"]["rows"] <= 0.05 * 255)
        return {"H1": a == n, "H2": b == n, "H3": c == n and cm <= 4.5, "H4": d == n, "H5": f == n,
                "counts": (a, b, c, cm, d, f, n)}
    p = ev([e for e in eps if e["salt"] == "primary"])
    r = ev([e for e in eps if e["salt"] == "replication"])
    for k in ("H1", "H2", "H3", "H4"):
        ck(p[k], f"{k} primary")
    ck(p["H5"] is False, "H5 primary failed as pre-registered")
    ck(r["H5"] is True, "H5 replication passed")
    ck(all(r[k] for k in ("H1", "H2", "H3", "H4", "H5")), "H6 replication")
    for k in ("H1_full_complement_sound", "H2_base_certificate_blind", "H3_rotating_lease_bound",
              "H4_complement_lease", "H6_replication"):
        ck(rep["hypotheses"][k]["verdict"] == "SUPPORTED", f"reported {k}")
    ck(rep["hypotheses"]["H5_price_of_cheap_audit"]["verdict"] == "NOT_SUPPORTED", "reported H5")
    ck(rep["hypotheses"]["H7_external_review"]["verdict"] == "BLOCKED", "H7")
    ck(rep["verdict"] == "NOT_SUPPORTED_EXCEPTION_RECOVERY", "verdict negative")
    ck(rep["replication_verdict"] == "SUPPORTED", "replication verdict")
    a = rep["summaries"]["all"]
    ck(a["final_correct"]["LEASE_32"] == 24 and a["final_correct"]["LEASE_COMPLEMENT"] == 24, "summary exact")
    ck(a["wrong_uses_max"]["LEASE_CERT"] == 50, "summary cert blind")
    for k in ("FULL_COMPLEMENT", "BASE_CERT", "SAMPLE_64"):
        ck(abs(a["cert_cost_mean"][k] - sum(e["certifications"][k]["rows"] for e in eps) / 24) < 1e-9,
           f"summary cert cost {k}")

    try:
        from cryptography.hazmat.primitives import serialization
        body = {k: v for k, v in man.items() if k != "signature"}
        pub = serialization.load_pem_public_key((b / "E368X_PUBKEY.pem").read_bytes())
        pub.verify(bytes.fromhex(man["signature"]), canon(body)); ck(True, "manifest signature")
    except Exception as ex:
        ck(False, "manifest signature", str(ex))
    files = sorted(p for p in b.rglob("*") if p.is_file() and p.name not in
                   {"E368X_MANIFEST.json", "E368X_SIGNED_BODY.json", "E368X_VERIFICATION_RESULTS.json",
                    "E368X_TAMPER_RESULTS.json", "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json",
                    "E368X_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")
    ck(not any(p.suffix == ".py" and "verify" not in p.name and "tamper" not in p.name for p in files), "no source")
    ck(any(p.name == "verify_e368x_offline.py" for p in files), "verifier shipped")
    print(f"E368-X 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 "."))
