#!/usr/bin/env python3
"""Standalone verifier for the Shared Memory RSI evidence bundle.

Imports no CAIN code. Verifies:
  * the signed manifest (Ed25519) and every listed file SHA-256;
  * the recomputed Merkle root;
  * every memory row signature and the per-tenant hash chain;
  * every hypothesis and the verdict, recomputed from the raw rows and sealed results;
  * the partition row count, the poisoned-claim control, and the no-authority invariants.

Usage: python3 verify_smr_offline.py <bundle-dir>
Exit 0 only if every check passes.
"""
from __future__ import annotations

import hashlib
import json
import sys
from pathlib import Path

from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey

S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
GENS = 6
SALTS = ("primary", "replication")
CHECKS: list[tuple[str, bool]] = []


def check(name: str, ok: bool) -> None:
    CHECKS.append((name, bool(ok)))


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 merkle(hashes: list[str]) -> str:
    l = sorted(hashes)
    if not l:
        return sha(b"")
    while len(l) > 1:
        if len(l) % 2:
            l.append(l[-1])
        l = [sha((l[i] + l[i + 1]).encode()) for i in range(0, len(l), 2)]
    return l[0]


def curve(evals: list[dict]) -> list[int]:
    out = []
    for g in range(GENS):
        vals = [int(e["dev"].get("accepted", 0)) for e in evals if int(e["gen"]) <= g]
        out.append(max(vals) if vals else 0)
    return out


def stats_for(rows: list[dict], sealed: list[dict]) -> dict:
    c = curve(rows)
    best = c[-1] if c else 0
    gens = next((i for i, v in enumerate(c) if v == best), GENS - 1)
    fb = max(rows, key=lambda x: (int(x["dev"].get("accepted", 0)),
                                  -int(x["dev"].get("queries", 10 ** 9)),
                                  x["strategy_key"])) if rows else None
    return {
        "auc": sum(c), "curve": c, "gens_to_best": gens,
        "final_best": int(fb["dev"].get("accepted", 0)) if fb else 0,
        "sealed_mean": (sum(int(s["dev"]["accepted"]) for s in sealed) / len(sealed)) if sealed else 0.0,
        "sealed_false": sum(int(s["dev"]["false_accept"]) for s in sealed),
        "per_gen": {str(g): sum(1 for e in rows if int(e["gen"]) == g) for g in range(GENS)},
        "unique": len({e["strategy_key"] for e in rows}),
    }


def mem_ok(m: dict) -> bool:
    return all(bool(m.get(k)) for k in ("chain_ok", "forge_refused", "replay_refused",
                                        "tamper_detected", "tenant_isolated",
                                        "authority_refused", "grants_authority_false"))


def verify_memory(mem: dict) -> tuple[bool, int]:
    pubkeys = mem["public_keys"]
    all_ok = True
    row_count = 0
    for mem_block in mem["memories"]:
        prev = ""
        for r in mem_block["rows"]:
            row_count += 1
            entry = {"schema": "cain42.smr.memory.entry.v1", "tenant": r["tenant"], "agent": r["agent"],
                     "kind": r["kind"], "key": r["key"], "value": r["value"],
                     "confidence": float(r["confidence"]), "nonce": r["nonce"],
                     "prev_hash": r["prev_hash"], "created_at": float(r["created_at"])}
            payload = canon(entry)
            ok = (r["prev_hash"] == prev
                  and sha(payload + bytes.fromhex(r["sig"])) == r["entry_hash"])
            if ok:
                try:
                    Ed25519PublicKey.from_public_bytes(bytes.fromhex(pubkeys[r["agent"]])).verify(
                        bytes.fromhex(r["sig"]), payload)
                except (InvalidSignature, ValueError):
                    ok = False
            all_ok = all_ok and ok
            prev = r["entry_hash"]
    # the poisoned copy is a separate, deliberately modified chain start: verify signatures only
    for r in mem.get("poison_copy", []):
        entry = {"schema": "cain42.smr.memory.entry.v1", "tenant": r["tenant"], "agent": r["agent"],
                 "kind": r["kind"], "key": r["key"], "value": r["value"],
                 "confidence": float(r["confidence"]), "nonce": r["nonce"],
                 "prev_hash": r["prev_hash"], "created_at": float(r["created_at"])}
        payload = canon(entry)
        ok = sha(payload + bytes.fromhex(r["sig"])) == r["entry_hash"]
        if ok:
            try:
                Ed25519PublicKey.from_public_bytes(bytes.fromhex(pubkeys[r["agent"]])).verify(
                    bytes.fromhex(r["sig"]), payload)
            except (InvalidSignature, ValueError):
                ok = False
        all_ok = all_ok and ok
    return all_ok, row_count


def main(bundle: Path) -> int:
    man = json.loads((bundle / "SMR_MANIFEST.json").read_text())
    body = {k: v for k, v in man.items() if k != "signature"}
    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(
            bytes.fromhex(man["signature"]), canon(body))
        check("manifest signature", True)
    except Exception:
        check("manifest signature", False)
    files_ok = True
    for rel, h in man["files"].items():
        p = bundle / rel
        files_ok = files_ok and p.exists() and sha(p.read_bytes()) == h
    check(f"file hashes ({len(man['files'])})", files_ok)
    check("merkle root", merkle(list(man["files"].values())) == man["merkle_root"])

    report = json.loads((bundle / "SMR_RUN_REPORT.json").read_text())
    rows = json.loads((bundle / "SMR_ROWS.json").read_text())["rows"]
    sealed = json.loads((bundle / "SMR_SEALED.json").read_text())["sealed"]
    analysis = json.loads((bundle / "SMR_ANALYSIS.json").read_text())
    mem = json.loads((bundle / "SMR_MEMORY.json").read_text())
    poison = report["poison"]

    check("status line", report["status"] == S)
    check("zero model calls", report["resources"]["model_calls"] == 0 and report["resources"]["api_spend_usd"] == 0.0)
    check("zero weights", report["resources"]["weights_trained"] == 0)

    ok_rows, n_rows = verify_memory(mem)
    check(f"memory signatures and chains ({n_rows} rows)", ok_rows)

    st = {}
    for arm in ("shared", "isolated", "partitioned"):
        for salt in SALTS:
            key = f"{arm}|{salt}"
            st[key] = stats_for([r for r in rows if r["arm"] == arm and r["salt"] == salt],
                                sealed.get(key, []))

    doc = analysis["arms"]
    exact = 0
    for key, s in st.items():
        d = doc[key]
        exact += int(s["auc"] == d["auc"] and s["curve"] == d["curve"]
                     and s["gens_to_best"] == d["gens_to_best"]
                     and s["final_best"] == d["final_best"]["accepted"])
        exact += int(abs(s["sealed_mean"] - d["sealed_mean_accepted"]) < 1e-9
                     and s["sealed_false"] == d["sealed_false_accepts"])
    check(f"arm statistics recomputed ({len(st)} arms)", exact == 2 * len(st))

    h1 = all(st[f"shared|{s}"]["auc"] > st[f"isolated|{s}"]["auc"] for s in SALTS)
    h2 = all(st[f"shared|{s}"]["sealed_mean"] >= st[f"isolated|{s}"]["sealed_mean"]
             and st[f"shared|{s}"]["sealed_false"] == 0 for s in SALTS)
    parity = all(all(v == 8 for v in st[f"shared|{s}"]["per_gen"].values())
                 and all(v == 8 for v in st[f"isolated|{s}"]["per_gen"].values()) for s in SALTS)
    h3 = parity and all(st[f"shared|{s}"]["gens_to_best"] <= st[f"isolated|{s}"]["gens_to_best"] for s in SALTS)
    h4 = all(st[f"partitioned|{s}"]["final_best"] == st[f"shared|{s}"]["final_best"]
             and st[f"partitioned|{s}"]["sealed_mean"] >= st[f"shared|{s}"]["sealed_mean"] - 1
             and doc[f"partitioned|{s}"]["memory"].get("chain_ok") is True
             and doc[f"partitioned|{s}"]["memory"].get("rows") == 40 for s in SALTS)
    h5 = all(mem_ok(doc[f"{a}|{s}"]["memory"]) for a in ("shared", "partitioned") for s in SALTS) and (
        poison["trusting_uses_poison"]
        and poison["trusting_sealed_accepted"] < poison["governed_best_sealed_accepted"]
        and poison["governed_reverify_dev_accepted"] < poison["claimed_accepted"])
    h6 = h1 and h2 and h3 and h4 and h5
    check("H1 compounding AUC", h1 == (analysis["hypotheses"]["H1_memory_compounds_auc"]["verdict"] == "SUPPORTED"))
    check("H2 sealed non-inferior, zero false", h2 == (analysis["hypotheses"]["H2_shared_sealed_non_inferior_zero_false"]["verdict"] == "SUPPORTED"))
    check("H3 speed at equal compute", h3 == (analysis["hypotheses"]["H3_shared_reaches_best_no_slower_at_equal_compute"]["verdict"] == "SUPPORTED"))
    check("H4 partition recovery", h4 == (analysis["hypotheses"]["H4_partition_recovery"]["verdict"] == "SUPPORTED"))
    check("H5 integrity + no authority", h5 == (analysis["hypotheses"]["H5_memory_integrity_and_no_authority"]["verdict"] == "SUPPORTED"))
    check("H6 replication", h6 == (analysis["hypotheses"]["H6_replication_H1_H5"]["verdict"] == "SUPPORTED"))
    expected = ("SHARED_MEMORY_COMPOUNDING_SUPPORTED" if (h1 and h2 and h3 and h4 and h5)
                else "PARTIAL" if (h2 and h5) else "NOT_SUPPORTED")
    check("verdict recomputed", expected == report["verdict"] == analysis["verdict"])
    check("partition wrote exactly 40 rows, refused 8",
          all(doc[f"partitioned|{s}"]["memory"].get("rows") == 40
              and doc[f"partitioned|{s}"]["memory"].get("writes_refused") == 8 for s in SALTS))
    check("shared wrote 48 rows", all(doc[f"shared|{s}"]["memory"].get("rows") == 48 for s in SALTS))
    check("poison claim refuted by re-run",
          poison["claimed_accepted"] == 99 and poison["governed_reverify_dev_accepted"] < 99
          and poison["trusting_sealed_accepted"] < poison["governed_best_sealed_accepted"])
    check("external review not claimed", report.get("external_review", "NOT_OBTAINED") == "NOT_OBTAINED"
          or analysis["hypotheses"]["H7_external_review"]["verdict"] == "BLOCKED")

    passed = sum(1 for _, ok in CHECKS if ok)
    for name, ok in CHECKS:
        print(("PASS " if ok else "FAIL ") + name)
    print(f"{passed}/{len(CHECKS)} checks")
    return 0 if passed == len(CHECKS) else 1


if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("usage: verify_smr_offline.py <bundle-dir>")
        raise SystemExit(2)
    raise SystemExit(main(Path(sys.argv[1])))
