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

Imports no CAIN code. It re-verifies the signed manifest and every memory chain, then
recomputes each arm statistic, each adoption decision and the quorum law (an att(k) arm
adopts a signed lie iff k < m) from the shipped rows alone, and re-derives the verdict.
"""
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"
HONEST = ("h0", "h1", "h2", "h3")
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, n = True, 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 adoption_ok(a):
    """Recompute one adoption attempt from its signed inputs."""
    policy, k, m = a["policy"], a.get("k"), a["m"]
    claimed, target_score = int(a["claimed"]), int(a["target_score"])
    scores, own_claimed = list(a["own_scores"]), list(a["own_claimed"])
    if policy == "borrow":
        adopters = [x for i, x in enumerate(HONEST) if target_score > scores[i]]
        ok = bool(adopters) == bool(a["adopted"]) and adopters == list(a["adopters"])
        if a.get("is_lie"):
            ok = ok and bool(a["adopted"])
        return ok, adopters
    if policy == "verify":
        obs = a.get("observed") or {}
        adopters = [x for i, x in enumerate(HONEST)
                    if int(obs.get(x, -1)) >= claimed - 1 and claimed >= own_claimed[i]]
        ok = bool(adopters) == bool(a["adopted"]) and adopters == list(a["adopters"])
        if a.get("is_lie"):
            ok = ok and not a["adopted"]
        return ok, adopters
    confirmed = 0
    for att in a.get("attestations") or []:
        if att.get("insider"):
            confirmed += 1
        elif int(att.get("observed", -1)) >= claimed - 1:
            confirmed += 1
    passed = confirmed >= int(k)
    adopters = [x for i, x in enumerate(HONEST) if passed and claimed >= own_claimed[i]]
    ok = (confirmed == int(a["confirmations"]) and bool(adopters) == bool(a["adopted"])
          and adopters == list(a["adopters"]))
    return ok, adopters


def main(bundle: Path) -> int:
    man = json.loads((bundle / "QMR_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 / "QMR_RUN_REPORT.json").read_text())
    rows = json.loads((bundle / "QMR_ROWS.json").read_text())["rows"]
    sealed = json.loads((bundle / "QMR_SEALED.json").read_text())["sealed"]
    atts = json.loads((bundle / "QMR_ATTESTATIONS.json").read_text())["attestations"]
    adopt = json.loads((bundle / "QMR_ADOPTION.json").read_text())["arms"]
    ana = json.loads((bundle / "QMR_ANALYSIS.json").read_text())
    mem = json.loads((bundle / "QMR_MEMORY.json").read_text())
    poison_key = mem["poison_key"]

    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 key present", len(poison_key) > 10)
    check("attestation rows recorded", len(atts) > 0 and all("confirmed" in x for x in atts))

    def stats(aid, salt):
        e = [x for x in rows if x["arm"] == aid and x["salt"] == salt]
        s = sealed[f"{aid}|{salt}"]
        blocks = adopt[f"{aid}|{salt}"]["attempts"]
        attempts = [b for b in blocks if b.get("attempted")]
        proposal = sum(len(x["dev"].get("per_world", [])) for x in e)
        verify_w = sum(int(b.get("verify_worlds", 0)) for b in attempts)
        attest_w = sum(int(b.get("attest_worlds", 0)) for b in attempts)
        return {"dev_worlds": proposal + verify_w + attest_w,
                "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("poison")),
                "lie_adopted": sum(1 for b in attempts if b.get("is_lie") and b.get("adopted")),
                "true_adopted": sum(1 for b in attempts if not b.get("is_lie") and b.get("adopted")),
                "attempts": attempts}

    exact = 0
    total_attempts = 0
    for key, arm in adopt.items():
        aid, salt = key.split("|")
        st = stats(aid, salt)
        ok_a = True
        for b in st["attempts"]:
            total_attempts += 1
            good, _ = adoption_ok(b)
            ok_a = ok_a and good
        got = ana["arms"][salt][aid]
        exact += int(ok_a and abs(st["dev_worlds"] - got["dev_worlds"]) == 0
                     and abs(st["sealed_mean"] - got["sealed_mean"]) < 1e-9
                     and st["poison_adopted"] == got["poison_adopted"]
                     and st["lie_adopted"] == got["lie_adopted"]
                     and st["true_adopted"] == got["true_adopted"])
    check(f"arm statistics + adoption decisions recomputed ({len(adopt)} arms, "
          f"{total_attempts} attempts)", exact == len(adopt))

    h1 = h2 = h3 = h4 = True
    for salt in SALTS:
        verify = stats("verify", salt)
        for key, arm in adopt.items():
            aid, s = key.split("|")
            if s != salt:
                continue
            st = stats(aid, salt)
            if arm["policy"] == "att":
                for b in st["attempts"]:
                    if b.get("is_lie"):
                        if bool(b["adopted"]) != (int(arm["k"]) < int(b["m"])):
                            h1 = False
            if aid == "borrow" and st["lie_adopted"] < 1:
                h1 = False
            if aid == "verify" and st["lie_adopted"] != 0:
                h1 = False
        for key, arm in adopt.items():
            aid, s = key.split("|")
            if s != salt:
                continue
            if arm["policy"] != "att" or int(arm["k"]) < int(arm["m"]):
                continue
            st = stats(aid, salt)
            if st["true_adopted"] < 1 or st["sealed_mean"] < verify["sealed_mean"] - 1:
                h2 = False
        m1 = stats("att1_m1", salt)["dev_worlds"] < verify["dev_worlds"]
        m2 = stats("att2_m2", salt)["dev_worlds"] < verify["dev_worlds"]
        m3 = stats("att3_m3", salt)["dev_worlds"] > stats("att2_m2", salt)["dev_worlds"]
        h3 = h3 and m1 and m2 and m3
        h4 = h4 and mem_ok(ana["hypotheses"]["H4_memory_integrity_and_no_authority"]["detail"])
    h5 = h1 and h2 and h3 and h4
    expected = ("QUORUM_ATTESTATION_LAW_SUPPORTED" if (h1 and h2 and h3 and h4)
                else "PARTIAL" if (h1 and h4 and h2) else "NOT_SUPPORTED")
    hy = ana["hypotheses"]
    check("H1 quorum safety law", h1 == (hy["H1_quorum_safety_law"]["verdict"] == "SUPPORTED"))
    check("H2 safe-quorum liveness", h2 == (hy["H2_liveness_of_safe_quorum"]["verdict"] == "SUPPORTED"))
    check("H3 quorum cost curve", h3 == (hy["H3_cost_of_the_quorum"]["verdict"] == "SUPPORTED"))
    check("H4 integrity + no authority", h4 == (hy["H4_memory_integrity_and_no_authority"]["verdict"] == "SUPPORTED"))
    check("H5 replication", h5 == (hy["H5_replication"]["verdict"] == "SUPPORTED"))
    check("verdict recomputed", expected == rep["verdict"] == ana["verdict"])
    check("external review not claimed", hy["H6_external_review"]["verdict"] == "BLOCKED")
    check("borrow adopts the lie, verify does not",
          all(stats("borrow", s)["poison_adopted"] >= 1 and stats("verify", s)["poison_adopted"] == 0
              for s in SALTS))
    att_keys = [(key, arm) for key, arm in adopt.items() if arm["policy"] == "att"]
    check("every k>=m att arm rejects the lie",
          all(all(not b["adopted"] for b in stats(key.split("|")[0], key.split("|")[1])["attempts"]
                  if b.get("is_lie") and int(arm["k"]) >= int(b["m"]))
              for key, arm in att_keys))
    check("every k<m att arm adopts the lie",
          all(all(b["adopted"] for b in stats(key.split("|")[0], key.split("|")[1])["attempts"]
                  if b.get("is_lie") and int(arm["k"]) < int(b["m"]))
              for key, arm in att_keys))

    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_qmr_offline.py <bundle-dir>")
    raise SystemExit(main(Path(sys.argv[1])))
