#!/usr/bin/env python3
"""E393-M auditor: verify a compacted, quorum-ordered memory log fetched from the replica.

Checks (no CAIN imports): replica metadata; the signed compaction checkpoint; the old-head quorum
receipt; every retained entry's signature, declared gap and quorum receipt; the destroyed entries are
absent; destruction receipts verify; the export carries ciphertext only.
"""
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 base(e):
    return {"schema": "cain42.memory.entry.v5", "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 entry(e):
    return dict(base(e), quorum_sequence=int(e["quorum_sequence"]),
                quorum_digest=e["quorum_digest"])

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
    log = (d / "memory.jsonl").read_bytes()
    lines = [json.loads(l) for l in log.splitlines() if l.strip()]
    cp_file = json.loads((d / "CHECKPOINT.json").read_text())
    old = json.loads((d / "OLD_HEAD_RECEIPT.json").read_text())
    receipts = json.loads((d / "QUORUM_RECEIPTS.json").read_text())
    mem = json.loads((d / "MEMBERSHIP.json").read_text())
    dest = json.loads((d / "DESTRUCTIONS.json").read_text())
    rep = json.loads((d / "REPLICA.json").read_text())
    checks = []
    def ck(n, ok): checks.append((n, bool(ok)))
    ck("replica metadata", rep.get("sha256") == sha(log)
       and int(rep.get("lines", -1)) == len(lines))
    cp = lines[0] if lines else {}
    ck("checkpoint is the first line", cp.get("entry_hash") == cp_file.get("entry_hash")
       and cp.get("schema") == "cain42.memory.compaction.v1")
    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(cp["custodian_pubkey"])).verify(
            bytes.fromhex(cp["sig"]), canon({k: v for k, v in cp.items() if k != "sig"}))
        ck("checkpoint signature", True)
    except Exception:
        ck("checkpoint signature", False)
    ck("old-head receipt verifies", V.verify_receipt(old, pin=V.Q.h(mem),
                                                    digest=cp.get("old_head"))["verdict"] == "NOTARIZED")
    entries = lines[1:]
    hashes = [e["entry_hash"] for e in entries]
    ck("retained set matches", hashes == cp.get("retained"))
    ck("destroyed absent", all(h not in hashes for h in cp.get("destroyed", [])))
    known = set(hashes) | set(cp.get("destroyed", []))
    broken, sigs, quorum_ok = 0, 0, 0
    prev_ok = True
    for e in entries:
        payload = canon(entry(e))
        pub = None
        # the agent key is in the checkpoint's agent map? put it in the checkpoint
        agents = cp.get("agents", {})
        pub = agents.get(e["agent"])
        ok = e["prev"] in known 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 sha(canon(base(e))) == e.get("quorum_digest") and e["quorum_digest"] in receipts:
            r = receipts[e["quorum_digest"]]
            if V.verify_receipt(r, pin=V.Q.h(mem), digest=e["quorum_digest"])["verdict"] == "NOTARIZED":
                quorum_ok += 1
    ck("retained signatures", broken == 0 and sigs == len(entries))
    ck("retained quorum receipts", quorum_ok == len(entries))
    ck("no plaintext or key", not any(("value" in e or "wrapped" in e or "plaintext" in e) for e in entries))
    ck("destroyed ciphertext absent", all(
        base64.b64decode(e["ciphertext"]).decode(errors="ignore") not in ("",) for e in entries))
    dest_ok = 0
    for h, r in dest.items():
        try:
            Ed25519PublicKey.from_public_bytes(bytes.fromhex(r["custodian_pubkey"])).verify(
                bytes.fromhex(r["sig"]), canon({k: v for k, v in r.items() if k != "sig"}))
            if h in cp.get("destroyed", []) and r["entry_hash"] == h:
                dest_ok += 1
        except Exception:
            pass
    ck("destruction receipts", dest_ok == len(dest) and len(dest) >= 1)
    ck("entries present", len(entries) >= 5)
    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())
