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

Recomputes the detection round/rows from the stored verification order, checks every
policy decision against the observed function and the reported audit rows, recomputes
H1-H6 and the verdict, and validates the chain, salt commitments, manifest signature,
Merkle root and engine-source withholding.
"""
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 as_int(x):
    return x if isinstance(x, int) else int(x, 16)


def bit(mask, r):
    return (as_int(mask) >> r) & 1


def main(d):
    b = Path(d)
    rep = json.loads((b / "E361_RUN_REPORT.json").read_text())
    pre = json.loads((b / "E361_PREREGISTRATION.json").read_text())
    man = json.loads((b / "E361_MANIFEST.json").read_text())
    freeze = json.loads((b / "E361_PREREGISTRATION_FREEZE.json").read_text())
    salts = json.loads((b / "E361_SALT_REVEALED.json").read_text())
    S = rep["config"]["sweep"]
    ck(rep["schema"] == "cain42.e361.run.v1", "schema")
    ck(rep["evolution"] == "E361", "evolution")
    ck(rep["model_calls"] == 0 and rep["api_spend_usd"] == 0.0, "zero model calls / spend")
    ck(sha((b / "E361_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) == 72, "72 episodes", len(eps))
    ck(sum(1 for e in eps if e["salt"] == "primary") == 36, "36 primary")
    ck(sum(1 for e in eps if e["salt"] == "replication") == 36, "36 replication")
    for e in eps:
        tag = e["id"]
        f, r0 = e["f_mask"], e["r0_mask"]
        changed = int(f, 16) ^ int(r0, 16)
        ck(e["drift"] == "IN_CLASS" or e["f_in_class"] is False, f"{tag} out-of-class flag")
        ck(e["drift"] != "IN_CLASS" or e["f_in_class"] is True, f"{tag} in-class flag")
        # detection from the stored order
        cert = e["cert_rows"]
        order = e["order"]
        ck(len(order) == 256, f"{tag} order length")
        ck(order[:len(cert)] == cert, f"{tag} order starts with certificate")
        rows = [r for r in cert if (changed >> r) & 1]
        rnd = 1 if rows else None
        if not rows:
            for j in range(0, len(order) - len(cert), S):
                block = order[len(cert) + j:len(cert) + j + S]
                rows = [r for r in block if (changed >> r) & 1]
                if rows:
                    rnd = j // S + 1
                    break
        ck(e["detected"] == (rnd is not None), f"{tag} detected flag")
        ck(e["detection_round"] == rnd, f"{tag} detection round")
        ck(sorted(e["detected_rows"]) == sorted(rows), f"{tag} detected rows")
        # every changed row for one/two-row must be detected
        if e["drift"] != "IN_CLASS":
            ck(all(r in e["detected_rows"] for r in range(256) if (changed >> r) & 1),
               f"{tag} all changed rows detected")
        # labels agree with F
        for k, v in e["labels"].items():
            ck(((int(f, 16) >> int(k)) & 1) == v, f"{tag} label {k}")
        for pol, p in e["policies"].items():
            used = p.get("used_rows", [])
            if p["accepted_mask"] is not None:
                am = as_int(p["accepted_mask"])
                ck(all(((am >> r) & 1) == ((int(f, 16) >> r) & 1) for r in used),
                   f"{tag} {pol} accepted agrees with used rows")
                ck(p["correct"] == (am == int(f, 16)), f"{tag} {pol} correct flag")
                ck(p["false_accept"] == (am != int(f, 16)), f"{tag} {pol} false accept flag")
            else:
                ck(p["correct"] is False and p["false_accept"] is False, f"{tag} {pol} no acceptance flags")
            if pol == "KEEP_OLD":
                ck(as_int(p["accepted_mask"]) == int(r0, 16), f"{tag} keep old is R0")
            if pol == "QUARANTINE":
                ck(p["accepted"] is False, f"{tag} quarantine refuses")
            if pol == "FAIL_CLOSED" and p["accepted"]:
                ck(all(((as_int(p["accepted_mask"]) >> r) & 1) == ((int(f, 16) >> r) & 1)
                       for r in e["audit_rows"]), f"{tag} fail-closed audit")
                ck(set(p["used_rows"]) == set(e["sample_rows"]) | set(e["audit_rows"]),
                   f"{tag} fail-closed used rows")
            if pol == "TARGETED_CERT":
                for t in p.get("tried", []):
                    cm = as_int(t["mask"])
                    ok = all(((cm >> r) & 1) == ((int(f, 16) >> r) & 1) for r in t["cert_rows"])
                    ck(t["audit_pass"] == ok, f"{tag} cert audit {t['mask'][:8]}")
                if p["accepted"]:
                    ck(any(as_int(t["mask"]) == as_int(p["accepted_mask"]) and t["audit_pass"]
                           for t in p.get("tried", [])), f"{tag} accepted has a passing certificate")
                    ck(set(p["used_rows"]) == set(e["detected_rows"]) | set(e["sample_rows"]),
                       f"{tag} targeted used rows")
    # chain
    prev = "0" * 64
    ok_chain = True
    for i, row in enumerate(rep["chain"]):
        base = {k: v for k, v in eps[i].items() if k != "labels"}
        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, "episode chain")
    ck(len(rep["chain"]) == 72, "chain length")

    def ev(group):
        n = len(group)
        ic = [e for e in group if e["drift"] == "IN_CLASS"]
        one = [e for e in group if e["drift"] == "ONE_ROW"]
        out = [e for e in group if e["drift"] != "IN_CLASS"]
        def c(rows, pol, key):
            return sum(1 for e in rows if e["policies"][pol][key])
        return {
            "H1": c(ic, "KEEP_OLD", "correct") == 0,
            "H2": c(one, "FORCE", "false_accept") >= len(one) // 2,
            "H3": c(one, "FAIL_CLOSED", "false_accept") >= len(one) // 2,
            "H4": c(out, "TARGETED_CERT", "false_accept") == 0 and c(ic, "TARGETED_CERT", "correct") >= int(0.8 * len(ic)),
            "H5": c(group, "QUARANTINE", "false_accept") == 0 and c(ic, "QUARANTINE", "correct") == 0,
            "counts": (n, len(ic), len(one), len(out)),
        }
    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", "H5"):
        ck(p[k], f"{k} primary")
    ck(all(r[k] for k in ("H1", "H2", "H3", "H4", "H5")), "H6 replication")
    for k in ("H1_keep_old_never_correct", "H2_force_false_accepts", "H3_random_audit_false_accepts",
              "H4_certificate_gated_recovery", "H5_quarantine_safe_not_live", "H6_replication"):
        ck(rep["hypotheses"][k]["verdict"] == "SUPPORTED", f"reported {k}")
    ck(rep["hypotheses"]["H7_external_review"]["verdict"] == "BLOCKED", "H7 blocked")
    ck(rep["verdict"] == "CERTIFICATE_GATED_RECOVERY_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
    a = rep["summaries"]["all"]
    ck(sum(a["false_accept"].values()) >= 0, "summary present")
    ck(a["false_accept"]["TARGETED_CERT"] == 0, "summary targeted 0 false accepts")
    ck(a["in_class_correct"]["TARGETED_CERT"] >= 20, "summary targeted recovery")
    ck(a["false_accept"]["QUARANTINE"] == 0 and a["in_class_correct"]["QUARANTINE"] == 0, "summary quarantine")

    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 / "E361_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
                   {"E361_MANIFEST.json", "E361_SIGNED_BODY.json", "E361_VERIFICATION_RESULTS.json",
                    "E361_TAMPER_RESULTS.json", "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json",
                    "E361_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_e361_offline.py" for p in files), "verifier shipped")

    print(f"E361 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 "."))
