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

Rebuilds every store from its seed, then recomputes the honest, fork and rewind heads, checks that the
fork and the prefix are valid chains, and recomputes every scenario's per-mechanism detection and cost.
Then H1-H5/H8 on primary and replication, the pooled verdict, the dev-only selection, the row chain,
the salt commitments, the manifest signature, no unlisted files and no engine source.
"""
from __future__ import annotations

import hashlib
import json
import sys
from pathlib import Path

FAILS = []
CHECKS = [0]
AGENTS = 8
RECORDS = 32
SCENARIOS = ("HONEST", "FORK_ONE", "REWIND_ONE", "FORK_ALL", "REWIND_ALL")
ATTACKS = ("FORK_ONE", "REWIND_ONE", "FORK_ALL", "REWIND_ALL")
MECHS = ("LOCAL", "HEAD_GOSSIP", "FULL_GOSSIP", "ANCHOR")
HEAD_BYTES = 40
RECORD_BYTES = 128


def ck(cond, name, detail=""):
    CHECKS[0] += 1
    if not cond:
        FAILS.append(f"{name}: {detail}")


def sha(b):
    return hashlib.sha256(b if isinstance(b, bytes) else b.encode()).hexdigest()


def canon(o):
    return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()


def build_store(seed: int):
    prev = "0" * 64
    out = []
    for i in range(RECORDS):
        rec = {"i": i, "agent": f"agent-{i % AGENTS}", "kind": ("action", "record", "result")[i % 3],
               "payload": f"r{i}-{seed % 100000}", "prev": prev}
        rec["hash"] = sha(canon(rec))
        prev = rec["hash"]
        out.append(rec)
    return out


def head(records):
    return (records[-1]["hash"], len(records)) if records else ("0" * 64, 0)


def valid(records):
    prev = "0" * 64
    for r in records:
        body = {k: r[k] for k in ("i", "agent", "kind", "payload", "prev")}
        if r["prev"] != prev or r["hash"] != sha(canon(body)):
            return False
        prev = r["hash"]
    return True


def fork(records, idx=10, tag="fork"):
    out = [dict(r) for r in records]
    out[idx]["payload"] = out[idx]["payload"] + "-" + tag
    prev = out[idx - 1]["hash"]
    for j in range(idx, len(out)):
        out[j]["prev"] = prev
        body = {k: out[j][k] for k in ("i", "agent", "kind", "payload", "prev")}
        out[j]["hash"] = sha(canon(body))
        prev = out[j]["hash"]
    return out


def detect(heads, anchor, mech):
    if mech == "LOCAL":
        return False
    if mech in ("HEAD_GOSSIP", "FULL_GOSSIP"):
        return len(set(heads)) > 1
    if mech == "ANCHOR":
        return any(hd != anchor for hd in heads)
    raise ValueError(mech)


def cost(mech):
    msgs = AGENTS * (AGENTS - 1) // 2
    return {"LOCAL": 0, "HEAD_GOSSIP": msgs * HEAD_BYTES, "FULL_GOSSIP": msgs * RECORDS * RECORD_BYTES,
            "ANCHOR": AGENTS * HEAD_BYTES}[mech]


def main(d):
    b = Path(d)
    rep = json.loads((b / "E382_RUN_REPORT.json").read_text())
    pre = json.loads((b / "E382_PREREGISTRATION.json").read_text())
    man = json.loads((b / "E382_MANIFEST.json").read_text())
    freeze = json.loads((b / "E382_PREREGISTRATION_FREEZE.json").read_text())
    salts = json.loads((b / "E382_SALT_REVEALED.json").read_text())
    dev = json.loads((b / "E382_DEVIATIONS.json").read_text())

    ck(rep["schema"] == "cain42.e382.run.v1", "schema")
    ck(rep["evolution"] == "E382", "evolution")
    ck(rep["model_calls"] == 0 and rep["api_spend_usd"] == 0.0 and rep["weights_changed"] == 0, "zero resources")
    ck(sha((b / "E382_PREREGISTRATION.json").read_bytes()) == freeze["preregistration_sha256"], "prereg freeze hash")
    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(dev.get("deviations") == [], "no deviations")

    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")
    for x in insts:
        tag = x["id"]
        base = build_store(x["store_seed"])
        anchor = head(base)
        forked = head(fork(base, 10, "a"))
        rewound = head(base[:24])
        ck(x["agents"] == AGENTS and x["records"] == RECORDS, f"{tag} config")
        ck((x["anchor_head"], x["anchor_len"]) == anchor, f"{tag} anchor")
        ck(x["honest_head"] == anchor[0], f"{tag} honest head")
        ck(x["fork_head"] == forked[0] and x["rewind_head"] == rewound[0] and x["rewind_len"] == rewound[1], f"{tag} attack heads")
        ck(x["all_valid"] == {"fork": valid(fork(base, 10, "a")), "rewind": valid(base[:24])}, f"{tag} validity")
        ck(x["all_valid"]["fork"] is True and x["all_valid"]["rewind"] is True, f"{tag} attack chains valid")
        views = {"HONEST": [anchor] * AGENTS}
        v = [anchor] * AGENTS; v[3] = forked; views["FORK_ONE"] = v
        v = [anchor] * AGENTS; v[5] = rewound; views["REWIND_ONE"] = v
        views["FORK_ALL"] = [forked] * AGENTS
        views["REWIND_ALL"] = [rewound] * AGENTS
        ck(set(x["scenarios"]) == set(SCENARIOS), f"{tag} scenarios")
        for sc in SCENARIOS:
            ck(x["scenarios"][sc]["_heads_distinct"] == len(set(views[sc])), f"{tag} {sc} distinct heads")
            for m in MECHS:
                got = x["scenarios"][sc][m]
                ck(got["detected"] == detect(views[sc], anchor, m), f"{tag} {sc} {m} detected")
                ck(got["cost_bytes"] == cost(m), f"{tag} {sc} {m} cost")

    def sm(lst):
        n = len(lst)
        return {"instances": n,
                **{sc: {m: {"detected": sum(1 for x in lst if x["scenarios"][sc][m]["detected"]) / n,
                           "cost_bytes": lst[0]["scenarios"][sc][m]["cost_bytes"]} for m in MECHS}
                   for sc in SCENARIOS}}
    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)
        ck(got["instances"] == want["instances"], f"summary {label} instances")
        for sc in SCENARIOS:
            for m in MECHS:
                ck(abs(got[sc][m]["detected"] - want[sc][m]["detected"]) < 1e-12, f"summary {label} {sc} {m} detected")
                ck(got[sc][m]["cost_bytes"] == want[sc][m]["cost_bytes"], f"summary {label} {sc} {m} cost")

    def ev(lst, sel):
        n = len(lst)

        def d(x, sc, m):
            return x["scenarios"][sc][m]["detected"]
        h1 = sum(1 for x in lst if all(not d(x, a, "LOCAL") for a in ATTACKS))
        h2a = sum(1 for x in lst if d(x, "FORK_ONE", "HEAD_GOSSIP") and d(x, "REWIND_ONE", "HEAD_GOSSIP"))
        h2b = sum(1 for x in lst if not d(x, "FORK_ALL", "HEAD_GOSSIP") and not d(x, "REWIND_ALL", "HEAD_GOSSIP"))
        h3 = sum(1 for x in lst if all(d(x, a, "ANCHOR") for a in ATTACKS))
        h4a = sum(1 for x in lst if all(d(x, a, "FULL_GOSSIP") == d(x, a, "HEAD_GOSSIP") for a in ATTACKS))
        h4b = sum(1 for x in lst if cost("FULL_GOSSIP") >= 10 * cost("HEAD_GOSSIP"))
        h5 = sum(1 for x in lst if all(not d(x, "HONEST", m) for m in MECHS))
        h8 = sum(1 for x in lst if all(d(x, a, sel) for a in ATTACKS))
        return {
            "H1_local_is_blind": ("SUPPORTED" if h1 == n else "NOT_SUPPORTED", h1),
            "H2_gossip_detects_split_only": ("SUPPORTED" if (h2a == n and h2b == n) else "NOT_SUPPORTED", h2a),
            "H3_anchor_detects_all": ("SUPPORTED" if h3 == n else "NOT_SUPPORTED", h3),
            "H4_full_gossip_is_not_better": ("SUPPORTED" if (h4a == n and h4b == n) else "NOT_SUPPORTED", h4a),
            "H5_honest_no_false_positive": ("SUPPORTED" if h5 == n else "NOT_SUPPORTED", h5),
            "H8_dev_selection": ("SUPPORTED" if (sel == "ANCHOR" and h8 == n) else "NOT_SUPPORTED", h8),
        }
    for label, lst in (("primary", prim), ("replication", repl)):
        for k, (v, _) in ev(lst, rep["selection"]["selected"]).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, rep["selection"]["selected"]).items())
    rep_ok = all(v == "SUPPORTED" for k, (v, _) in ev(repl, rep["selection"]["selected"]).items())
    ck(rep["verdict"] == ("EQUIVOCATION_NEEDS_ANCHOR" if (ok and rep_ok) else "NOT_SUPPORTED"), "pooled 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")

    rows = []
    for m in MECHS:
        detected = sum(1 for x in rep["dev_instances"] for a in ATTACKS if x["scenarios"][a][m])
        rows.append({"mechanism": m, "detected": detected, "cost_bytes": cost(m)})
    pub = {c["mechanism"]: c for c in rep["selection"]["candidates"]}
    for r in rows:
        ck(pub[r["mechanism"]]["detected"] == r["detected"] and pub[r["mechanism"]]["cost_bytes"] == r["cost_bytes"], f"selection candidate {r['mechanism']}")
    eligible = [r for r in rows if r["detected"] == len(ATTACKS) * len(rep["dev_instances"])]
    eligible.sort(key=lambda r: (r["cost_bytes"], MECHS.index(r["mechanism"])))
    ck(eligible[0]["mechanism"] == rep["selection"]["selected"], "selection recomputed")

    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

    ck(man["merkle_root"] == (b / "MERKLE_ROOT.txt").read_text().strip(), "merkle 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
        pubk = serialization.load_pem_public_key((b / "E382_PUBKEY.pem").read_bytes())
        pubk.verify(bytes.fromhex(man["signature"]), canon(body))
        ck(True, "manifest signature")
    except Exception as e:  # noqa: BLE001
        ck(False, "manifest signature", str(e)[:120])
    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")
    disk = {str(p.relative_to(b)) for p in b.rglob("*") if p.is_file()
            and str(p.relative_to(b)) not in
            {"E382_MANIFEST.json", "E382_SIGNED_BODY.json", "E382_TAMPER_RESULTS.json",
             "E382_VERIFICATION_RESULTS.json", "MANIFEST.json", "MERKLE_ROOT.txt",
             "PUBLICATION.json", "E382_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")

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