#!/usr/bin/env python3
"""Standalone verifier for the Shared Memory RSI — Borrow or Re-run bundle."""
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"
SALTS = ("primary", "replication")
CHECKS = []


def check(n, ok):
    CHECKS.append((n, bool(ok)))


def sha(b):
    return hashlib.sha256(b).hexdigest()


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


def merkle(hs):
    l = sorted(hs)
    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 mem_ok(m):
    return all(bool(m.get(k)) for k in ("chain_ok", "tenant_isolated", "forge_refused", "replay_refused",
                                        "tamper_detected", "authority_refused", "grants_authority_false"))


def verify_memory(mem):
    pub = mem["public_keys"]
    ok = True
    n = 0
    for block in mem["memories"]:
        prev = ""
        for r in block["rows"]:
            n += 1
            e = {"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"])}
            p = canon(e)
            good = r["prev_hash"] == prev and sha(p + bytes.fromhex(r["sig"])) == r["entry_hash"]
            if good:
                try:
                    Ed25519PublicKey.from_public_bytes(bytes.fromhex(pub[r["agent"]])).verify(
                        bytes.fromhex(r["sig"]), p)
                except (InvalidSignature, ValueError):
                    good = False
            ok = ok and good
            prev = r["entry_hash"]
    return ok, n


def main(bundle: Path) -> int:
    man = json.loads((bundle / "SMRB_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)
    fok = all((bundle / r).exists() and sha((bundle / r).read_bytes()) == h for r, h in man["files"].items())
    check(f"file hashes ({len(man['files'])})", fok)
    check("merkle root", merkle(list(man["files"].values())) == man["merkle_root"])

    rep = json.loads((bundle / "SMRB_RUN_REPORT.json").read_text())
    rows = json.loads((bundle / "SMRB_ROWS.json").read_text())["rows"]
    sealed = json.loads((bundle / "SMRB_SEALED.json").read_text())["sealed"]
    ana = json.loads((bundle / "SMRB_ANALYSIS.json").read_text())
    mem = json.loads((bundle / "SMRB_MEMORY.json").read_text())
    poison = set(mem["poison_keys"])

    check("status line", rep["status"] == S)
    check("zero model calls / spend", rep["resources"]["model_calls"] == 0 and rep["resources"]["api_spend_usd"] == 0.0)
    check("zero weights", rep["resources"]["weights_trained"] == 0)
    ok, n = verify_memory(mem)
    check(f"memory signatures and chains ({n} rows)", ok)
    check("poison keys present", len(poison) == 2 and all(len(k) > 10 for k in poison))

    def st(arm, salt):
        e = [x for x in rows if x["arm"] == arm and x["salt"] == salt]
        s = sealed[f"{arm}|{salt}"]
        return {"dev_worlds": sum(len(x["dev"].get("per_world", [])) for x in e),
                "evals": len(e),
                "sealed_mean": sum(x["dev"]["accepted"] for x in s) / len(s) if s else 0.0,
                "poison_adopted": sum(1 for x in s if x.get("adopted_key") in poison),
                "adopted": int(ana["arms"][salt][arm]["adopted"])}

    exact = 0
    for salt in SALTS:
        for arm in ("isolated", "verify", "borrow", "borrow_audit"):
            a, d = st(arm, salt), ana["arms"][salt][arm]
            exact += int(a["dev_worlds"] == d["dev_worlds"] and a["evals"] == d["evaluations"]
                         and abs(a["sealed_mean"] - d["sealed_mean"]) < 1e-9
                         and a["poison_adopted"] == d["poison_adopted"])
    check("arm statistics recomputed (8 arms)", exact == 8)

    h1 = h2 = h3 = True
    for salt in SALTS:
        v, b, ba = st("verify", salt), st("borrow", salt), st("borrow_audit", salt)
        h1s = b["dev_worlds"] <= 0.65 * v["dev_worlds"]
        h2s = b["poison_adopted"] >= 1 and v["poison_adopted"] == 0 and b["sealed_mean"] <= v["sealed_mean"] - 2
        h3s = ba["dev_worlds"] <= 0.75 * v["dev_worlds"] and ba["sealed_mean"] >= v["sealed_mean"] - 1
        h1, h2, h3 = h1 and h1s, h2 and h2s, h3 and h3s
    # H4's live probes are reported by the run; the verifier independently re-verifies every
    # memory signature and chain above, then checks the reported probe booleans.
    h4 = mem_ok(ana["hypotheses"]["H4_memory_integrity_and_no_authority"]["detail"])
    h5 = h1 and h2 and h3 and h4
    expected = ("BORROW_TRADEOFF_MEASURED" if (h1 and h2 and h3 and h4)
                else "PARTIAL" if (h2 and h4) else "NOT_SUPPORTED")
    check("H1 borrow saves compute", h1 == (ana["hypotheses"]["H1_borrow_saves_compute"]["verdict"] == "SUPPORTED"))
    check("H2 borrow buys the liar", h2 == (ana["hypotheses"]["H2_borrow_buys_the_liar"]["verdict"] == "SUPPORTED"))
    check("H3 audit keeps truth cheaply", h3 == (ana["hypotheses"]["H3_audit_keeps_truth_cheaply"]["verdict"] == "SUPPORTED"))
    check("H4 integrity + no authority", h4 == (ana["hypotheses"]["H4_memory_integrity_and_no_authority"]["verdict"] == "SUPPORTED"))
    check("H5 replication", h5 == (ana["hypotheses"]["H5_replication"]["verdict"] == "SUPPORTED"))
    check("verdict recomputed", expected == rep["verdict"] == ana["verdict"])
    check("borrow adopts poison, verify does not",
          all(st("borrow", s)["poison_adopted"] >= 1 and st("verify", s)["poison_adopted"] == 0 for s in SALTS))
    check("verify audits zero", all(st("verify", s)["adopted"] == 0 for s in SALTS))
    check("external review not claimed", ana["hypotheses"]["H6_external_review"]["verdict"] == "BLOCKED")

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


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