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

Rebuilds every store, checks the honest and fork heads, and recomputes each anchor interval's
anchored prefix, window, anchors, and every policy's accepted/hidden value. 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 math
import sys
from pathlib import Path

FAILS = []
CHECKS = [0]
RECORDS = 61
FORK_AT = 60
A_VALUES = (2, 4, 8, 16, 32)
MECHS = ("OPTIMISTIC", "PREFIX", "INCLUSION")


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, n=RECORDS):
    prev = "0" * 64
    out = []
    for i in range(n):
        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=FORK_AT, 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 interval_cell(A):
    anchored = (RECORDS // A) * A
    window = RECORDS - anchored
    anchors = math.ceil(RECORDS / A)
    return {"A": A, "anchored": anchored, "window": window, "anchors": anchors,
            "OPTIMISTIC": {"accepted": window > 0, "hidden": 0, "anchors": anchors},
            "PREFIX": {"accepted": False, "hidden": window, "anchors": anchors},
            "INCLUSION": {"accepted": False, "hidden": window, "anchors": anchors}}


def main(d):
    b = Path(d)
    rep = json.loads((b / "E385_RUN_REPORT.json").read_text())
    pre = json.loads((b / "E385_PREREGISTRATION.json").read_text())
    man = json.loads((b / "E385_MANIFEST.json").read_text())
    freeze = json.loads((b / "E385_PREREGISTRATION_FREEZE.json").read_text())
    salts = json.loads((b / "E385_SALT_REVEALED.json").read_text())
    dev = json.loads((b / "E385_DEVIATIONS.json").read_text())

    ck(rep["schema"] == "cain42.e385.run.v1", "schema")
    ck(rep["evolution"] == "E385", "evolution")
    ck(rep["model_calls"] == 0 and rep["api_spend_usd"] == 0.0 and rep["weights_changed"] == 0, "zero resources")
    ck(sha((b / "E385_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"])
        forked = fork(base)
        ck(x["records"] == RECORDS and x["fork_at"] == FORK_AT, f"{tag} config")
        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 and head(forked)[0] != head(base)[0], f"{tag} fork differs")
        ck(set(x["intervals"]) == {str(A) for A in A_VALUES}, f"{tag} intervals")
        for A in A_VALUES:
            cell = x["intervals"][str(A)]
            want = interval_cell(A)
            ck(cell["A"] == A and cell["anchored"] == want["anchored"] and cell["window"] == want["window"]
               and cell["anchors"] == want["anchors"], f"{tag} A={A} interval")
            for m in MECHS:
                ck(cell[m]["accepted"] == want[m]["accepted"] and cell[m]["hidden"] == want[m]["hidden"]
                   and cell[m]["anchors"] == want[m]["anchors"], f"{tag} A={A} {m}")
        ew = x["every_write"]
        ck(ew["window"] == 0 and ew["accepted"] is False and ew["hidden"] == 0 and ew["anchors"] == RECORDS, f"{tag} every write")

    def sm(lst):
        n = len(lst)
        out = {"instances": n}
        for A in A_VALUES:
            key = str(A)
            out[key] = {"A": A, "window": lst[0]["intervals"][key]["window"], "anchored": lst[0]["intervals"][key]["anchored"],
                        "anchors": lst[0]["intervals"][key]["anchors"]}
            for m in MECHS:
                out[key][m] = {"accepted": sum(1 for x in lst if x["intervals"][key][m]["accepted"]) / n,
                               "hidden": sum(x["intervals"][key][m]["hidden"] for x in lst) / n}
        out["every_write"] = {"accepted": sum(1 for x in lst if x["every_write"]["accepted"]) / n,
                              "hidden": sum(x["every_write"]["hidden"] for x in lst) / n,
                              "anchors": lst[0]["every_write"]["anchors"], "window": 0}
        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 A in A_VALUES:
            for kk in ("window", "anchored", "anchors"):
                ck(got[str(A)][kk] == want[str(A)][kk], f"summary {label} A={A} {kk}")
            for m in MECHS:
                for kk in ("accepted", "hidden"):
                    ck(abs(got[str(A)][m][kk] - want[str(A)][m][kk]) < 1e-12, f"summary {label} A={A} {m} {kk}")
        for kk in ("accepted", "hidden", "anchors", "window"):
            ck(got["every_write"][kk] == want["every_write"][kk], f"summary {label} every_write {kk}")

    def ev(lst, sel):
        n = len(lst)
        h1 = sum(1 for x in lst if all(x["intervals"][str(A)]["OPTIMISTIC"]["accepted"] for A in A_VALUES) and not x["every_write"]["accepted"])
        h2 = sum(1 for x in lst for A in A_VALUES for m in ("PREFIX", "INCLUSION")
                 if not x["intervals"][str(A)][m]["accepted"] and x["intervals"][str(A)][m]["hidden"] == x["intervals"][str(A)]["window"])
        h3 = sum(1 for x in lst if x["every_write"]["window"] == 0 and x["every_write"]["hidden"] == 0
                 and x["every_write"]["anchors"] == RECORDS and not x["every_write"]["accepted"])
        h4 = sum(1 for x in lst if all(x["intervals"][str(A)]["window"] == RECORDS % A for A in A_VALUES))
        h8 = 0
        for x in lst:
            if sel == "ANCHOR_EVERY_WRITE":
                ok = (not x["every_write"]["accepted"]) and x["every_write"]["hidden"] <= 2
                mine = x["every_write"]["anchors"]
            else:
                m, a = sel.split("_A")
                cell = x["intervals"][a]
                ok = (not cell[m]["accepted"]) and cell[m]["hidden"] <= 2
                mine = cell[m]["anchors"]
            cands = [x["every_write"]["anchors"]] if (not x["every_write"]["accepted"] and x["every_write"]["hidden"] <= 2) else []
            cands += [x["intervals"][str(A)][m2]["anchors"] for A in A_VALUES for m2 in ("PREFIX", "INCLUSION")
                      if not x["intervals"][str(A)][m2]["accepted"] and x["intervals"][str(A)][m2]["hidden"] <= 2]
            h8 += 1 if (ok and cands and mine == min(cands)) else 0
        return {
            "H1_optimistic_accepts_the_window": ("SUPPORTED" if h1 == n else "NOT_SUPPORTED", h1),
            "H2_prefix_and_inclusion_hide_it": ("SUPPORTED" if h2 == n * len(A_VALUES) * 2 else "NOT_SUPPORTED", h2),
            "H3_anchor_every_write_closes_it": ("SUPPORTED" if h3 == n else "NOT_SUPPORTED", h3),
            "H4_window_is_the_remainder": ("SUPPORTED" if h4 == n else "NOT_SUPPORTED", h4),
            "H8_dev_selection": ("SUPPORTED" if (sel == "PREFIX_A4" 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_FRESHNESS_NEEDED" 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"]["H5_replication"]["verdict"] == ("SUPPORTED" if rep_ok else "NOT_SUPPORTED"), "H5 derived")
    ck(rep["hypotheses"]["H6_external_review"]["verdict"] == "BLOCKED", "H6 blocked")

    rows = []
    for A in A_VALUES:
        for m in ("PREFIX", "INCLUSION"):
            rows.append({"policy": f"{m}_A{A}", "mechanism": m, "A": A,
                         "accepted": any(x["intervals"][str(A)][m]["accepted"] for x in rep["dev_instances"]),
                         "hidden": max(x["intervals"][str(A)][m]["hidden"] for x in rep["dev_instances"]),
                         "anchors": rep["dev_instances"][0]["intervals"][str(A)][m]["anchors"]})
    rows.append({"policy": "ANCHOR_EVERY_WRITE", "mechanism": "ANCHOR_EVERY_WRITE", "A": 1,
                 "accepted": any(x["every_write"]["accepted"] for x in rep["dev_instances"]), "hidden": 0,
                 "anchors": rep["dev_instances"][0]["every_write"]["anchors"]})
    pub = {c["policy"]: c for c in rep["selection"]["candidates"]}
    for r in rows:
        ck(pub[r["policy"]]["accepted"] == r["accepted"] and pub[r["policy"]]["hidden"] == r["hidden"]
           and pub[r["policy"]]["anchors"] == r["anchors"], f"selection candidate {r['policy']}")
    eligible = [r for r in rows if not r["accepted"] and r["hidden"] <= 2]
    eligible.sort(key=lambda r: (r["anchors"], r["hidden"], 0 if r["mechanism"] == "PREFIX" else 1, 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 / "E385_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
            {"E385_MANIFEST.json", "E385_SIGNED_BODY.json", "E385_TAMPER_RESULTS.json",
             "E385_VERIFICATION_RESULTS.json", "MANIFEST.json", "MERKLE_ROOT.txt",
             "PUBLICATION.json", "E385_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]))
