#!/usr/bin/env python3
"""E391-M auditor: replay the exported memory chain from a clean copy.

Verifies (imports no CAIN code): every entry signature, the per-tenant hash chain, that the exported
head is the last entry hash, that the head equals the quorum receipt digest, and that the receipt
verifies offline against the pinned membership. A tampered export fails.
"""
from __future__ import annotations
import hashlib,json,sys
from pathlib import Path
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey

def canon(o): return json.dumps(o,sort_keys=True,separators=(",",":"),ensure_ascii=False).encode()
def sha(b): return hashlib.sha256(b).hexdigest()

def entry(e):
    return {"schema": "cain42.shared_memory.entry.v3", "tenant": e["tenant"], "agent": e["agent"],
            "key": e["key"], "value": e["value"], "kind": e["kind"],
            "confidence": float(e["confidence"]), "retain_until": float(e["retain_until"]),
            "nonce": e["nonce"], "prev": e["prev"], "created_at": float(e["created_at"])}

def main() -> int:
    d = Path(sys.argv[1] if len(sys.argv) > 1 else ".").resolve()
    for cand in (d, Path(__file__).resolve().parent,
                 Path(__file__).resolve().parents[3] / "scripts" / "cain42_bft"):
        if (Path(cand) / "verify_qaas_receipt.py").exists():
            sys.path.insert(0, str(cand)); break
    import verify_qaas_receipt as V
    exp = json.loads((d / "MEMORY_EXPORT.json").read_text())
    rec = json.loads((d / "QUORUM_RECEIPT.json").read_text())
    mem = json.loads((d / "MEMBERSHIP.json").read_text())
    checks = []
    def ck(n, ok): checks.append((n, bool(ok)))
    ck("schema", exp.get("schema") == "cain42.memory.export.v1")
    agents = exp["agents"]
    prev, broken, sigs, tombstones, tomb_ok = "", 0, 0, 0, 0
    known = set()
    for e in exp["entries"]:
        ok = e["prev"] == prev
        pub = agents.get(e["agent"], {}).get("pubkey")
        payload = canon(entry(e))
        ok = ok and bool(pub) and sha(payload + bytes.fromhex(e["sig"])) == e["entry_hash"]
        if ok:
            try:
                Ed25519PublicKey.from_public_bytes(bytes.fromhex(pub)).verify(
                    bytes.fromhex(e["sig"]), payload)
                sigs += 1
            except (InvalidSignature, ValueError):
                ok = False
        if not ok:
            broken += 1
        if e["kind"] == "deletion":
            tombstones += 1
            target = e["key"].split("deleted:", 1)[1] if e["key"].startswith("deleted:") else ""
            if target in known:
                tomb_ok += 1
        known.add(e["entry_hash"])
        prev = e["entry_hash"]
    ck("chain intact", broken == 0)
    ck("every signature verifies", sigs == len(exp["entries"]))
    ck("head is the last entry", exp["head"] == prev)
    ck("head equals the receipt digest", rec.get("digest") == exp["head"])
    v = V.verify_receipt(rec, pin=V.Q.h(mem), digest=exp["head"])["verdict"]
    ck("receipt verifies offline", v == "NOTARIZED")
    ck("entries present", len(exp["entries"]) >= 20)
    ck("tombstones target prior entries", tombstones == tomb_ok)

    rep_path = d / "E391M_RUN_REPORT.json"
    if rep_path.exists():
        rep = json.loads(rep_path.read_text())
        H = rep["hypotheses"]
        ck("report schema", rep.get("schema") == "cain42.e391m.run_report.v1")
        ck("report status line", rep.get("status") == "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL")
        ck("seal verified", H["H1_quorum_seal"]["verdict"] == "SUPPORTED")
        ck("auditor verdict", H["H2_auditor_verifies"]["verdict"] == "SUPPORTED")
        ck("grants", H["H3_read_grants"]["verdict"] == "SUPPORTED")
        ck("retention", H["H4_retention"]["verdict"] == "SUPPORTED")
        ck("deletion proof", H["H5_deletion_proof"]["verdict"] == "SUPPORTED")
        ck("tamper detected", H["H6_tamper_detected"]["verdict"] == "SUPPORTED")
        ck("verdict", rep.get("verdict") == "QUORUM_SEALED_MEMORY_PROOFS_SUPPORTED")
        ck("0 model calls", rep["resources"]["model_calls"] == 0)
        ck("limits", len(rep["limits"]) == 6)
    man_path = d / "E391M_MANIFEST.json"
    if man_path.exists():
        man = json.loads(man_path.read_text())
        EX = {"E391M_MANIFEST.json", "E391M_SIGNED_BODY.json", "E391M_VERIFICATION_RESULTS.json",
              "E391M_TAMPER_RESULTS.json", "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json",
              "E391M_OMEGA_SEAL.json"}
        files = sorted(p for p in d.rglob("*") if p.is_file() and str(p.relative_to(d)) not in EX
                       and "__pycache__" not in p.parts and not p.name.endswith(("-wal", "-shm")))
        ck("manifest files", man["files"] == {str(p.relative_to(d)): sha(p.read_bytes()) for p in files})
        leaves = sorted(sha(p.read_bytes()) for p in files)
        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("merkle root", man["merkle_root"] == (leaves[0] if leaves else sha(b"")))
        try:
            from cryptography.hazmat.primitives import serialization as _ser
            pk = _ser.load_pem_public_key((d / "E391M_PUBKEY.pem").read_bytes()) \
                if (d / "E391M_PUBKEY.pem").exists() else Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"]))
            body = {k: v for k, v in man.items() if k != "signature"}
            pk.verify(bytes.fromhex(man["signature"]), canon(body))
            ck("manifest signature", True)
        except Exception as e:  # noqa: BLE001
            ck(f"manifest signature ({type(e).__name__})", False)
    bad = [n for n, ok in checks if not ok]
    for n, ok in checks:
        print(("PASS " if ok else "FAIL ") + n)
    print(f"{len(checks)-len(bad)}/{len(checks)} checks passed")
    return 0 if not bad else 1

if __name__ == "__main__":
    sys.exit(main())
