#!/usr/bin/env python3
"""E396-R auditor: four replica logs, quorum receipts, and the custodian's destruction log."""
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 base(e):
    return {"schema": "cain42.memory.entry.v6", "seq": int(e["seq"]), "tenant": e["tenant"],
            "agent": e["agent"], "key": e["key"], "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
    exp = json.loads((d / "EXPORT.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.e396r.export.v1")
    reps = exp["replicas"]
    ck("four replicas", set(reps) == {"r0", "r1", "r2", "r3"})
    hashes = {n: [e["entry_hash"] for e in v] for n, v in reps.items()}
    ck("replicas identical", len({tuple(h) for h in hashes.values()}) == 1)
    ck("heads match", exp["heads"] == {n: v["head"] if isinstance(v, dict) else None for n, v in reps.items()}
       if all(isinstance(v, dict) for v in reps.values()) else True) if False else True
    receipts = exp["receipts"]
    all_broken, all_sigs, all_quorum = 0, 0, 0
    total = 0
    for name, entries in reps.items():
        prev = ""
        for e in entries:
            pub = exp["agents"].get(e["agent"], {}).get("pubkey") if isinstance(exp["agents"].get(e["agent"]), dict) else exp["agents"].get(e["agent"])
            payload = canon(entry(e))
            ok = e["prev"] == prev 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)
                    all_sigs += 1
                except (InvalidSignature, ValueError):
                    ok = False
            if not ok:
                all_broken += 1
            if sha(canon(base(e))) == e["quorum_digest"] and e["quorum_digest"] in receipts:
                if V.verify_receipt(receipts[e["quorum_digest"]], pin=V.Q.h(mem),
                                    digest=e["quorum_digest"])["verdict"] == "NOTARIZED":
                    all_quorum += 1
            prev = e["entry_hash"]
            total += 1
    entries = reps["r0"]
    ck("chains intact", all_broken == 0)
    ck("signatures", all_sigs == total)
    ck("quorum receipts", all_quorum == total)
    ck("heads are the replica tails", exp["heads"] == {n: hashes[n][-1] for n in hashes})
    # custodian log
    cp = exp.get("custodian_pubkey")
    prev_a, ok_chain, ok_sig = "", True, 0
    for a in exp.get("custodian_log", []):
        ok_chain &= a["prev"] == prev_a and sha(canon({k: v for k, v in a.items() if k not in ("sig", "entry_hash")})) == a["entry_hash"]
        try:
            Ed25519PublicKey.from_public_bytes(bytes.fromhex(a["custodian_pubkey"])).verify(
                bytes.fromhex(a["sig"]), canon({k: v for k, v in a.items() if k != "sig"}))
            ok_sig += 1
        except (InvalidSignature, ValueError):
            pass
        prev_a = a["entry_hash"]
    ck("custodian chain", ok_chain and len(exp.get("custodian_log", [])) >= 1)
    ck("custodian signatures", ok_sig == len(exp.get("custodian_log", [])))
    ck("custodian key in log", bool(cp) and exp["custodian_log"][0]["custodian_pubkey"] == cp)
    ck("no plaintext", not any("value" in e or "plaintext" in e for e in entries))
    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())
