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

import hashlib
import json
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 / "E363L_RUN_REPORT.json").read_text())
    pre = json.loads((b / "E363L_PREREGISTRATION.json").read_text())
    man = json.loads((b / "E363L_MANIFEST.json").read_text())
    freeze = json.loads((b / "E363L_PREREGISTRATION_FREEZE.json").read_text())
    salts = json.loads((b / "E363L_SALT_REVEALED.json").read_text())
    ck(rep["schema"] == "cain42.e363l.run.v1", "schema")
    ck(rep["evolution"] == "E363-L", "evolution")
    ck(rep["model_calls"] == 0 and rep["api_spend_usd"] == 0.0, "zero model calls / spend")
    ck(sha((b / "E363L_PREREGISTRATION.json").read_bytes()) == freeze["preregistration_sha256"], "prereg freeze hash")
    ck(pre["salt_commitment_sha256"] == rep["salt_commitment_sha256"], "salt commitments 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")

    eps = rep["episodes"]
    ck(len(eps) == 24, "24 instances", len(eps))
    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), f"{tag} f1")
        ck(f2 == int(e["f2_mask"], 16), f"{tag} f2")
        ck(e["r1"] != e["r2"], f"{tag} r1 != r2")
        ck(e["r1"] not in e["cert_rows"] and e["r2"] not in e["cert_rows"], f"{tag} drift rows outside certificate")
        ck(e["r1_in_class"] is False and e["r2_in_class"] is False, f"{tag} out-of-class drifts")
        p = e["policies"]
        ck(p["PERMANENT"]["wrong_uses"] == 50 and p["PERMANENT"]["detection_use"] is None, f"{tag} permanent")
        ck(p["FULL"]["wrong_uses"] == 0 and p["FULL"]["detection_use"] == 10, f"{tag} full check")
        ck(p["FULL"]["labels"] == 256 * 60, f"{tag} full labels")
        pos = e["lease_perm"].index(e["r2"])
        b32 = pos // 32
        det = 10 + ((b32 - 2) % 8)
        ck(p["ROTATE_32"]["detection_use"] == det, f"{tag} rotate detection")
        ck(p["ROTATE_32"]["wrong_uses"] == det - 10, f"{tag} rotate wrong uses")
        ck(p["ROTATE_32"]["labels"] == 32 * 60, f"{tag} rotate labels")
        b8 = pos // 8
        det8 = 10 + ((b8 - 10) % 32)
        ck(p["LEASE_8"]["detection_use"] == det8, f"{tag} lease8 detection")
        ck(p["LEASE_8"]["wrong_uses"] == det8 - 10, f"{tag} lease8 wrong uses")
        ck(p["LEASE_8"]["labels"] == 8 * 60, f"{tag} lease8 labels")
        s32 = p["SAMPLE_32"]
        ck(s32["labels"] == 32 * 60, f"{tag} sample labels")
        ck(s32["detection_use"] is None or 10 <= s32["detection_use"] < 60, f"{tag} sample detection range")
        ck(s32["wrong_uses"] == (50 if s32["detection_use"] is None else s32["detection_use"] - 10),
           f"{tag} sample wrong uses")
        for pol in ("SAMPLE_32", "ROTATE_32", "LEASE_8", "FULL"):
            ck(sorted(p[pol]["exceptions"]) == sorted({e["r1"], e["r2"]}), f"{tag} {pol} exceptions")
            ck(p[pol]["final_correct"] is True, f"{tag} {pol} final exact")
            ck(abs(p[pol]["labels_per_use"] - p[pol]["labels"] / 60) < 1e-9, f"{tag} {pol} labels/use")

    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["policies"]["PERMANENT"]["wrong_uses"] == 50)
        b = sum(1 for e in group if e["policies"]["SAMPLE_32"]["wrong_uses"] >= 1)
        c = sum(1 for e in group if e["policies"]["ROTATE_32"]["wrong_uses"] <= 7)
        cm = sum(e["policies"]["ROTATE_32"]["wrong_uses"] for e in group) / n
        d = sum(1 for e in group if e["policies"]["ROTATE_32"]["labels_per_use"] <= 0.15 * 256)
        f = sum(1 for e in group if e["policies"]["ROTATE_32"]["final_correct"]
                and e["policies"]["ROTATE_32"]["wrong_uses"] == e["policies"]["ROTATE_32"]["detection_use"] - 10)
        return {"H1": a == n, "H2": b >= n // 2, "H3": c == n and cm <= 4.5, "H4": d == n, "H5": f == n,
                "counts": (a, b, c, cm, d, f, n)}
    pr = ev([e for e in eps if e["salt"] == "primary"])
    rp = ev([e for e in eps if e["salt"] == "replication"])
    for k in ("H1", "H2", "H3", "H4", "H5"):
        ck(pr[k], f"{k} primary")
    ck(all(rp[k] for k in ("H1", "H2", "H3", "H4", "H5")), "H6 replication")
    for k in ("H1_permanent_always_wrong", "H2_sample_lease_wrong", "H3_rotating_lease_bound",
              "H4_rotating_lease_cost", "H5_rerecovery_exact", "H6_replication"):
        ck(rep["hypotheses"][k]["verdict"] == "SUPPORTED", f"reported {k}")
    ck(rep["hypotheses"]["H7_external_review"]["verdict"] == "BLOCKED", "H7 blocked")
    ck(rep["verdict"] == "RECOVERY_LEASE_SUPPORTED", "verdict")
    ck(rep["replication_verdict"] == ("SUPPORTED" if all(rp[k] for k in ("H1", "H2", "H3", "H4", "H5")) else "NOT_SUPPORTED"),
       "replication verdict")
    a = rep["summaries"]["all"]
    ck(a["wrong_uses_mean"]["PERMANENT"] == 50, "summary permanent")
    ck(a["wrong_uses_max"]["ROTATE_32"] <= 7, "summary rotate max")
    ck(a["final_correct"]["ROTATE_32"] == 24, "summary rotate exact")

    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 / "E363L_PUBKEY.pem").read_bytes())
        pub.verify(bytes.fromhex(man["signature"]), canon(body))
        ck(True, "manifest signature")
    except Exception as ex:  # pragma: no cover
        ck(False, "manifest signature", str(ex))
    files = sorted(p for p in b.rglob("*") if p.is_file() and p.name not in
                   {"E363L_MANIFEST.json", "E363L_SIGNED_BODY.json", "E363L_VERIFICATION_RESULTS.json",
                    "E363L_TAMPER_RESULTS.json", "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json",
                    "E363L_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_e363l_offline.py" for p in files), "verifier shipped")
    print(f"E363-L 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 "."))
