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

Rebuilds every store, checks the honest and fork heads, and recomputes every policy's boundary
(fooled iff c >= Q), cost, honest false positive and the dev-only selection. Then H1-H6/H8, the pooled
verdict, the row chain, the salt commitments, the manifest signature, no unlisted files, no engine source.
"""
from __future__ import annotations

import hashlib
import json
import sys
from pathlib import Path

FAILS = []
CHECKS = [0]
RECORDS = 32
POLICIES = (
    ("SINGLE", 1, 1), ("MAJ4", 4, 3), ("ALL4", 4, 4),
    ("MAJ7", 7, 4), ("BFT7", 7, 5), ("ALL7", 7, 7),
    ("MAJ10", 10, 6), ("BFT10", 10, 7), ("ALL10", 10, 10),
)
MAJORITIES = ("MAJ4", "MAJ7", "MAJ10")


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):
    prev = "0" * 64
    out = []
    for i in range(RECORDS):
        rec = {"i": i, "agent": f"agent-{i % 8}", "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=16, 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 main(d):
    b = Path(d)
    rep = json.loads((b / "E387_RUN_REPORT.json").read_text())
    pre = json.loads((b / "E387_PREREGISTRATION.json").read_text())
    man = json.loads((b / "E387_MANIFEST.json").read_text())
    freeze = json.loads((b / "E387_PREREGISTRATION_FREEZE.json").read_text())
    salts = json.loads((b / "E387_SALT_REVEALED.json").read_text())
    dev = json.loads((b / "E387_DEVIATIONS.json").read_text())

    ck(rep["schema"] == "cain42.e387.run.v1", "schema")
    ck(rep["evolution"] == "E387", "evolution")
    ck(rep["model_calls"] == 0 and rep["api_spend_usd"] == 0.0 and rep["weights_changed"] == 0, "zero resources")
    ck(sha((b / "E387_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(len(dev["deviations"]) == 1 and dev["deviations"][0]["id"] == "D1", "D1 recorded")

    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"])
        forked = fork(base)
        ck(x["records"] == RECORDS, f"{tag} records")
        ck(x["honest_head"] == head(base)[0] and x["fork_head"] == head(forked)[0], f"{tag} heads")
        ck(x["fork_valid"] == valid(forked) and x["fork_valid"] is True, f"{tag} fork valid")
        ck(x["fork_differs"] is True, f"{tag} fork differs")
        ck(set(x["policies"]) == {p[0] for p in POLICIES}, f"{tag} policies")
        for name, nn, Q in POLICIES:
            p = x["policies"][name]
            ck(p["n"] == nn and p["Q"] == Q and p["cost"] == Q and p["threshold"] == Q, f"{tag} {name} config")
            ck(set(p["fooled"]) == {str(c) for c in range(nn + 1)}, f"{tag} {name} counts")
            for c in range(nn + 1):
                ck(p["fooled"][str(c)] == (c >= Q), f"{tag} {name} c={c}")

    def sm(lst):
        n = len(lst)
        out = {"instances": n}
        for name, nn, Q in POLICIES:
            out[name] = {"n": nn, "Q": Q, "cost": Q,
                         "fooled": {str(c): sum(1 for x in lst if x["policies"][name]["fooled"][str(c)]) / n for c in range(nn + 1)}}
        return out
    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 name, _nn, _Q in POLICIES:
            for c, v in want[name]["fooled"].items():
                ck(abs(got[name]["fooled"][c] - v) < 1e-12, f"summary {label} {name} c={c}")

    def ev(lst, sel):
        n = len(lst)
        h1 = sum(1 for x in lst if x["policies"]["SINGLE"]["fooled"]["1"] is True)
        h2 = sum(1 for x in lst for name, nn, Q in POLICIES for c in range(nn + 1) if x["policies"][name]["fooled"][str(c)] == (c >= Q))
        h2tot = n * sum(nn + 1 for _name, nn, _Q in POLICIES)
        h3 = sum(1 for x in lst if all(x["policies"][m]["threshold"] > 1 for m in MAJORITIES))
        h4 = sum(1 for x in lst if all(x["policies"][name]["cost"] == Q for name, _nn, Q in POLICIES))
        h5 = sum(1 for x in lst if all(not x["policies"][name]["fooled"]["0"] for name, _nn, _Q in POLICIES))
        h8 = 0
        for x in lst:
            cands = [Q for name, nn, Q in POLICIES if Q - 1 >= 2]
            got = next((Q for name, nn, Q in POLICIES if name == sel), None)
            h8 += 1 if (got is not None and got - 1 >= 2 and got == min(cands) and not x["policies"][sel]["fooled"]["1"]) else 0
        return {
            "H1_single_anchor_is_one_colluder": ("SUPPORTED" if h1 == n else "NOT_SUPPORTED", h1),
            "H2_quorum_boundary": ("SUPPORTED" if h2 == h2tot else "NOT_SUPPORTED", h2),
            "H3_majority_tolerates_q_minus_one": ("SUPPORTED" if h3 == n else "NOT_SUPPORTED", h3),
            "H4_cost_is_the_quorum": ("SUPPORTED" if h4 == n else "NOT_SUPPORTED", h4),
            "H5_honest_no_false_positive": ("SUPPORTED" if h5 == n else "NOT_SUPPORTED", h5),
            "H8_dev_selection": ("SUPPORTED" if (sel == "MAJ4" 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"] == ("ANCHOR_QUORUM_LAW_SUPPORTED" 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 name, nn, Q in POLICIES:
        rows.append({"policy": name, "n": nn, "Q": Q, "cost": Q, "tolerated": Q - 1,
                     "fooled_at_1": any(x["policies"][name]["fooled"]["1"] for x in rep["dev_instances"])})
    pub = {c["policy"]: c for c in rep["selection"]["candidates"]}
    for r in rows:
        ck(pub[r["policy"]]["cost"] == r["cost"] and pub[r["policy"]]["tolerated"] == r["tolerated"]
           and pub[r["policy"]]["fooled_at_1"] == r["fooled_at_1"], f"selection candidate {r['policy']}")
    eligible = [r for r in rows if r["tolerated"] >= 2]
    eligible.sort(key=lambda r: (r["cost"], r["n"], r["policy"]))
    ck(eligible[0]["policy"] == 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 / "E387_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
            {"E387_MANIFEST.json", "E387_SIGNED_BODY.json", "E387_TAMPER_RESULTS.json",
             "E387_VERIFICATION_RESULTS.json", "MANIFEST.json", "MERKLE_ROOT.txt",
             "PUBLICATION.json", "E387_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]))
