#!/usr/bin/env python3
"""E422-X standalone offline verifier (stdlib + cryptography; imports no CAIN code).

It re-checks, from the shipped bundle alone:
  * the manifest Ed25519 signature and every declared file SHA-256;
  * the Merkle root recomputed from those hashes;
  * the frozen preregistration hash, the salt commitments and the revealed salts;
  * every memory chain: canonical body, SHA-256 link, prev link and Ed25519 signature,
    with the public key re-derived from the E380-M study key rule;
  * the budget claim: every arm spends the same development/probe episodes and labels;
  * every audit block's ranking, recomputed from its labelled rows and the signed probe
    masks: accuracy per candidate, the champion, and the captured arm's row identity;
  * the hypotheses and verdict rule recomputed from the raw curves;
  * the poison controls, the governance probes, the checkpoint hash chain and the
    no-models/no-spend record.

The engine is withheld under the IP rule, so the verifier does not re-execute the learner;
it recomputes the *selection* and the arithmetic from the exported data and checks that
the signed record is internally consistent. A PASS is not proof that the research claim
is true.
"""
from __future__ import annotations

import hashlib
import json
import sys
from pathlib import Path

from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey

STATUS = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
POISON = "single|random|10|20"
ARMS = ("none", "claimed", "reread8", "disagree", "disagree_captured")
SHARED = ("claimed", "reread8", "disagree", "disagree_captured")
SALTS = ("primary", "replication")
LABELS = 256
THRESH = {"rsi": 0.10, "collective": 0.10, "allocation": 0.05, "trust": 0.10}


def sha(b: bytes) -> str:
    return hashlib.sha256(b).hexdigest()


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


def load(p: Path):
    return json.loads(Path(p).read_text())


def derive_pub(agent: str) -> bytes:
    k = Ed25519PrivateKey.from_private_bytes(hashlib.sha256(("e380m|" + agent).encode()).digest())
    return k.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw)


class Checker:
    def __init__(self):
        self.rows = []

    def add(self, name: str, ok: bool, detail: str = "") -> None:
        self.rows.append({"check": name, "ok": bool(ok), "detail": detail})

    def finish(self) -> int:
        ok = sum(1 for r in self.rows if r["ok"])
        n = len(self.rows)
        for r in self.rows:
            print(f'{"PASS" if r["ok"] else "FAIL"}  {r["check"]}  {r["detail"]}')
        print(f"\n{ok}/{n} checks passed · {STATUS}")
        return 0 if ok == n else 1


def merkle(paths: list[Path]) -> str:
    leaves = sorted(sha(p.read_bytes()) for p in paths)
    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)]
    return leaves[0] if leaves else sha(b"")


def check_chain(ch: Checker, label: str, rows: list[dict]) -> None:
    prev = "0" * 64
    ok = sig_ok = canon_ok = True
    for r in rows:
        body = {"tenant": r["tenant"], "seq": r["seq"], "agent": r["agent"], "kind": r["kind"],
                "payload": r["payload"], "uncertainty": r["uncertainty"],
                "verification": r["verification"], "prev": r["prev"]}
        try:
            h = sha(canon(body) + bytes.fromhex(r["sig"]))
        except Exception:
            canon_ok = False
            break
        if h != r["hash"] or r["prev"] != prev:
            ok = False
            break
        try:
            Ed25519PublicKey.from_public_bytes(derive_pub(r["agent"])).verify(
                bytes.fromhex(r["sig"]), canon(body))
        except (InvalidSignature, ValueError):
            sig_ok = False
            break
        prev = r["hash"]
    ch.add(f"chain:{label}", ok and canon_ok and sig_ok,
           f"{len(rows)} rows, link={ok}, canonical={canon_ok}, signatures={sig_ok}")


def memory_parts(bundle: Path, salt: str, arm: str) -> list[tuple[str, list[dict]]]:
    p = bundle / "memory" / f"{salt}-{arm}.json"
    if not p.exists():
        return []
    doc = load(p)
    recs = doc.get("records") or []
    if recs and "rows" in (recs[0] or {}):
        return [(f"{p.stem}-{x.get('agent', '?')}", x.get("rows") or []) for x in recs]
    return [(p.stem, recs)]


def _mask(v):
    return None if v is None else int(v, 16)


def recompute_block(ch: Checker, b: dict, probe_masks: dict,
                    independent_rows: list[dict] | None) -> None:
    gen = int(b["gen"])
    label = f'{b["salt"]}|{b["arm"]}|g{b["gen"]}'
    rows = b.get("rows") or []
    cands = list((b.get("scores") or {}).keys())
    if not rows or not cands:
        ch.add(f"audit:{label}", False, "empty audit block")
        return
    ok = True
    recomputed = {}
    for p in cands:
        answered = k = 0
        for r in rows:
            m = _mask(((probe_masks.get((gen, p)) or {}).get(r["world"])))
            if m is None:
                continue
            answered += 1
            k += int(((m >> r["row"]) & 1) == int(r["label"]))
        acc = k / len(rows)          # an unanswered labelled row is wrong
        recomputed[p] = {"answered": answered, "accuracy": round(acc, 6)}
        stored = (b["scores"][p] or {}).get("accuracy")
        if stored is None or abs(float(stored) - round(acc, 6)) > 1e-9:
            ok = False
        stored_correct = (b["scores"][p] or {}).get("correct")
        if stored_correct is not None and int(stored_correct) != k:
            ok = False
        stored_answered = (b["scores"][p] or {}).get("answered")
        if stored_answered is not None and int(stored_answered) != answered:
            ok = False
    eligible = {p: s for p, s in recomputed.items()
                if s["answered"] and s["answered"] / max(1, len(rows)) >= 0.5}
    best = None
    if eligible:
        best = max(eligible, key=lambda p: (eligible[p]["accuracy"], p))
        if (b.get("champion") or {}).get("procedure") != best:
            ok = False
    if b.get("captured"):
        n_cap = sum(1 for r in rows if r.get("source") == "captured_candidate")
        ok = ok and n_cap >= 1          # the source is captured; the mix is a property of the poison
        if independent_rows is not None:
            a = sorted((r["world"], r["row"]) for r in rows)
            c = sorted((r["world"], r["row"]) for r in independent_rows)
            ok = ok and a == c
    ch.add(f"audit:{label}", ok,
           f"{len(rows)} labels, {len(cands)} candidates, champion={best}")


def block_of(report: dict, salt: str) -> dict:
    c = report["curves"]

    def v(arm, g):
        return float(c[f"{salt}|{arm}"][g]["sealed_accepted_correct"])
    d0, d1, d2 = v("disagree", 0), v("disagree", 1), v("disagree", 2)
    n2, r2 = v("none", 2), v("reread8", 2)
    c1c = c[f"{salt}|claimed"][1]["champion"]
    c1 = v("claimed", 1)
    cap1c = c[f"{salt}|disagree_captured"][1]["champion"]
    cap2 = v("disagree_captured", 2)
    out = {
        "H1": d2 - d0 >= THRESH["rsi"],
        "H2": d2 - n2 >= THRESH["collective"],
        "H3": d2 - r2 >= THRESH["allocation"],
        "H4": c1c == POISON and c1 <= d1 - THRESH["trust"],
        "H5": cap1c == POISON and cap2 < d2,
    }
    gov = report.get("governance") or {}
    out["H7"] = all((gov.get(f"{salt}|{a}") or {}).get("all_pass") is True for a in SHARED)
    return out


def main() -> int:
    b = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
    ch = Checker()
    man = load(b / "E422-X_MANIFEST.json")
    sig = man.pop("signature", "")
    pub = Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"]))
    try:
        pub.verify(bytes.fromhex(sig), (b / "E422-X_SIGNED_BODY.json").read_bytes())
        ch.add("manifest_signature", True, f'key {man["pubkey_fingerprint"]} (self-generated)')
    except (InvalidSignature, ValueError):
        ch.add("manifest_signature", False, "invalid")

    excluded = {"E422-X_MANIFEST.json", "E422-X_SIGNED_BODY.json",
                "E422-X_VERIFICATION_RESULTS.json", "MANIFEST.json", "MERKLE_ROOT.txt",
                "PUBLICATION.json", "E422-X_OMEGA_SEAL.json", "E422-X_TAMPER_RESULTS.json"}
    files = sorted(x for x in b.rglob("*") if x.is_file()
                   and str(x.relative_to(b)) not in excluded
                   and "__pycache__" not in x.parts)
    declared = man.get("files") or {}
    ch.add("file_hashes", all(declared.get(str(x.relative_to(b))) == sha(x.read_bytes())
                              for x in files) and len(declared) == len(files),
           f"{len(files)} files")
    ch.add("merkle_root", merkle(files) == man.get("merkle_root"), str(man.get("merkle_root"))[:16])

    fr = load(b / "E422-X_PREREGISTRATION_FREEZE.json")
    ch.add("prereg_hash", sha((b / "E422-X_PREREGISTRATION.json").read_bytes())
           == fr.get("preregistration_sha256"), str(fr.get("preregistration_sha256"))[:16])
    salt = load(b / "E422-X_SALT_REVEALED.json")["salts"]
    pre = load(b / "E422-X_PREREGISTRATION.json")
    ch.add("salt_commitments",
           all(sha(bytes.fromhex(v)) == pre["salt_commitment_sha256"][k] for k, v in salt.items()),
           "both salts match the frozen commitments")
    ch.add("engine_pins", len(fr.get("engine_sha256") or {}) >= 12,
           f"{len(fr.get('engine_sha256') or {})} engine files pinned (source withheld)")

    report = load(b / "E422-X_RUN_REPORT.json")
    hl = man.get("headline") or {}
    ch.add("headline_matches_report",
           hl.get("verdict") == report.get("verdict")
           and hl.get("primary_disagree") == [g["sealed_accepted_correct"]
                                              for g in report["curves"]["primary|disagree"]]
           and hl.get("poison_adopted_by_claimed") == (report["curves"]["primary|claimed"][1]["champion"] == POISON),
           "the manifest headline is the run report's headline")
    blocks = load(b / "E422-X_AUDIT_BLOCKS.json")["blocks"]
    by_block = {(x["salt"], x["arm"], x["gen"]): x for x in blocks}
    seen_blocks = 0
    for s in SALTS:
        for a in ARMS:
            parts = memory_parts(b, s, a)
            probe = {}
            for label, rows in parts:
                check_chain(ch, label, rows)
                for r in rows:
                    p = r["payload"]
                    if p.get("type") == "probe":
                        probe[(int(p["gen"]), p["procedure"])] = p["masks"]
            for g in range(3):
                blk = by_block.get((s, a, g))
                if blk is None:
                    if a == "claimed":
                        continue
                    ch.add(f"audit:{s}|{a}|g{g}", False, "missing audit block")
                    continue
                indep = by_block.get((s, "disagree", g)) if blk.get("captured") else None
                recompute_block(ch, blk, probe, (indep or {}).get("rows"))
                seen_blocks += 1
    ch.add("audit_blocks", seen_blocks >= 24, f"{seen_blocks} recomputed audit blocks")

    budgets = report.get("budgets") or {}
    same = len({(x["dev_episodes"], x["probe_episodes"], x["labels"]) for x in budgets.values()}) == 1
    ch.add("equal_budget", bool(same) and report.get("equal_budget") is True,
           "; ".join(f"{k}:{v['labels']} labels" for k, v in list(budgets.items())[:2]))
    ch.add("labels_per_generation",
           all(x["labels"] == 3 * LABELS for x in budgets.values()),
           f"every arm spends {3 * LABELS} labels over three generations")

    prim, repl = block_of(report, "primary"), block_of(report, "replication")
    h6 = all(prim[k] == repl[k] for k in prim)
    verdict = ("COLONY_SIGNAL_SUPPORTED" if (all(prim.values()) and h6)
               else "PARTIAL" if sum(prim.values()) >= 4 else "NOT_SUPPORTED")
    ch.add("verdict_recomputed", verdict == report.get("verdict"),
           f"{verdict} (report {report.get('verdict')})")
    ch.add("hypotheses_recomputed",
           all(report["hypotheses"][k]["verdict"] == ("SUPPORTED" if v else "NOT_SUPPORTED")
               for k, v in prim.items()), "primary H1-H5/H7 follow the raw curves")
    ch.add("replication_agrees",
           h6 == (report["hypotheses"]["H6"]["verdict"] == "SUPPORTED"),
           "H6 follows the primary/replication comparison")
    # The hypothesis verdicts (including H4/H5) are recomputed from the curves above.
    # The bundle must not assert an outcome the design did not guarantee (e.g. that the
    # captured auditor promotes the exact poison identity rather than another wrong rule).

    cp = report.get("checkpoints") or []
    ok, prev = True, "0" * 64
    for c in cp:
        if c["prev"] != prev:
            ok = False
            break
        body_c = {k: c[k] for k in ("label", "at", "payload", "prev")}
        prev = sha(json.dumps(body_c, sort_keys=True, separators=(",", ":")).encode())
        if prev != c["hash"]:
            ok = False
            break
    ch.add("checkpoint_chain", ok, f"{len(cp)} checkpoints")
    d = report.get("design") or {}
    ch.add("no_models_no_spend", d.get("model_calls") == 0 and d.get("api_spend_usd") == 0.0,
           "0 model calls, $0 API")
    return ch.finish()


if __name__ == "__main__":
    raise SystemExit(main())
