#!/usr/bin/env python3
"""RVP packet verifier — for an EXTERNAL reviewer.

Checks the FDC forecast docket (certificate signature, scope root, five member seals/Merkle roots,
and re-runs each member's own auditor), and optionally verifies a signed external-review attestation.

  python3 verify_packet.py --fdc <fdc-bundle-dir>
  python3 verify_packet.py --fdc <fdc-bundle-dir> --attestation attestation.json --reviewer-key key.pem
"""
import argparse, hashlib, json, subprocess, sys
from pathlib import Path
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey

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(ps):
    l = sorted(sha(p.read_bytes()) for p in ps)
    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] if l else sha(b"")

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("bundle", nargs="?")
    ap.add_argument("--fdc", default=None)
    ap.add_argument("--attestation")
    ap.add_argument("--reviewer-key")
    a = ap.parse_args()
    if a.fdc:
        root = Path(a.fdc)
    elif a.bundle:
        cand = Path(a.bundle) / "fdc"
        root = cand if cand.exists() else Path(a.bundle)
    else:
        root = Path(__file__).resolve().parent / "fdc"
    man = json.loads((root / "FDC_MANIFEST.json").read_text())
    body = {k: v for k, v in man.items() if k != "signature"}
    Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(bytes.fromhex(man["signature"]), canon(body))
    for n, h in man["files"].items():
        p = root / n
        if not p.exists() or sha(p.read_bytes()) != h: raise SystemExit(f"FAIL file {n}")
    if merkle([root / n for n in man["files"]]) != man["merkle_root"]: raise SystemExit("FAIL merkle")
    cert = json.loads((root / "FDC_CERTIFICATE.json").read_text())
    cbody = {k: v for k, v in cert.items() if k != "signature"}
    Ed25519PublicKey.from_public_bytes(bytes.fromhex(cert["pubkey_ed25519"])).verify(bytes.fromhex(cert["signature"]), canon(cbody))
    scope = json.loads((root / "FDC_SCOPE.json").read_text())
    if sha(canon(scope["members"])) != cert["scope_root"]: raise SystemExit("FAIL scope root")
    if [r["short"] for r in scope["members"] if r["verdict"] == "NOT_SUPPORTED"] != cert["negatives"]:
        raise SystemExit("FAIL negatives")
    for row in scope["members"]:
        d = root / "cited" / row["name"]
        p = subprocess.run([sys.executable, "-I", str(d / row["verifier"]), str(d)], capture_output=True, text=True, timeout=600)
        if p.returncode != 0: raise SystemExit(f"FAIL auditor {row['short']}")
        if row["seal_verdict"] != "ALLOWED": raise SystemExit(f"FAIL seal {row['short']}")
        if json.loads((d / f"{row['short']}_MANIFEST.json").read_text())["merkle_root"] != row["merkle_root"]:
            raise SystemExit(f"FAIL merkle {row['short']}")
    print(f"FDC OK: {len(scope['members'])} members, {cert['counts']['supported']} supported, "
          f"{cert['counts']['negatives']} preserved negative")
    if a.attestation:
        att = json.loads(Path(a.attestation).read_text())
        if att.get("schema") != "cain42.external-review.v1": raise SystemExit("FAIL attestation schema")
        if att.get("scope_root") != cert["scope_root"]: raise SystemExit("FAIL attestation scope")
        if att.get("verdict") not in ("ACCEPT", "REJECT", "LIMITATIONS"): raise SystemExit("FAIL attestation verdict")
        abody = {k: v for k, v in att.items() if k != "signature"}
        key = serialization.load_pem_public_key(Path(a.reviewer_key).read_bytes())
        key.verify(bytes.fromhex(att["signature"]), canon(abody))
        print(f"ATTESTATION OK: {att['verdict']} by {att.get('reviewer','?')} for scope {cert['scope_root'][:16]}…")
    return 0

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