#!/usr/bin/env python3
"""E392-M auditor: replay the memory log fetched from the independent replica.

Checks (imports no CAIN code): the replica metadata matches the fetched log; every entry signature
and the hash chain; the export head equals the last hash and the receipt digest; the receipt verifies
offline; the export carries ciphertext only (no value, plaintext or wrapped key); tombstones target
prior entries.
"""
from __future__ import annotations
import base64, 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.memory.entry.v4", "seq": int(e["seq"]), "tenant": e["tenant"],
            "agent": e["agent"], "key": e["key"], "kind": e["kind"],
            "confidence": float(e["confidence"]), "retain_until": float(e["retain_until"]),
            "prev": e["prev"], "key_id": e["key_id"], "ciphertext": e["ciphertext"],
            "ct_nonce": e["ct_nonce"], "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())
    rep = json.loads((d / "REPLICA.json").read_text())
    log = (d / "memory.jsonl").read_bytes()
    checks = []
    def ck(n, ok): checks.append((n, bool(ok)))
    ck("export schema", exp.get("schema") == "cain42.memory.export.v2")
    ck("replica metadata", rep.get("schema") == "cain42.memory.replica.v1"
       and rep.get("sha256") == sha(log)
       and exp.get("replica_sha256") == sha(log)
       and int(rep.get("lines", -1)) == len([l for l in log.splitlines() if l.strip()]))
    agents = exp["agents"]
    prev, broken, sigs = "", 0, 0
    known, tomb, tomb_ok = set(), 0, 0
    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
        try:
            base64.b64decode(e["ciphertext"], validate=True)
            base64.b64decode(e["ct_nonce"], validate=True)
        except Exception:
            broken += 1
        if e["kind"] == "deletion":
            tomb += 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("no plaintext or key in export", not any(
        ("value" in e or "plaintext" in e or "wrapped" in e or "data_key" in e) for e in exp["entries"]))
    ck("tombstones target prior entries", tomb == tomb_ok and tomb >= 1)
    ck("entries present", len(exp["entries"]) >= 10)
    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())
