#!/usr/bin/env python3
"""verify-attestation.py — verify a PropRaven Data Quality Attestation
in Python 3.9+. Two deps: cryptography + requests.

Usage:
    pip install cryptography requests
    curl -sL https://propraven.com/audit/verify-attestation.py | python3

Or:
    curl -O https://propraven.com/audit/verify-attestation.py
    python3 verify-attestation.py

Env override: PROPRAVEN_BASE=https://staging.propraven.com (default: production).
Exits 0 on PASS, 1 on any FAIL.
"""
import base64
import hashlib
import os
import sys

try:
    import requests
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
    from cryptography.exceptions import InvalidSignature
except ImportError as e:
    print(f"Missing dependency: {e.name}. Install with:")
    print("  pip install cryptography requests")
    sys.exit(1)


BASE = os.environ.get("PROPRAVEN_BASE", "https://propraven.com")


def fail(msg: str) -> "None":
    print(f"\n❌ FAIL — {msg}")
    sys.exit(1)


print("PropRaven Attestation Verifier (Python)")
print(f"Base: {BASE}\n")

print("1/4  Fetching artifacts...")
pdf = requests.get(f"{BASE}/audit/sample.pdf", timeout=30).content
manifest = requests.get(f"{BASE}/audit/sample.json", timeout=30).json()
pubkey_b64 = requests.get(f"{BASE}/audit/attestation-public-key.b64", timeout=30).text.strip()
print(f"      sample.pdf:  {len(pdf)} bytes")
print(f"      pubkey.b64:  {len(pubkey_b64)} chars\n")

print("2/4  Computing SHA-256 of PDF...")
actual = hashlib.sha256(pdf).hexdigest()
expected = manifest["content_hash_sha256"]
print(f"      actual:   {actual}")
print(f"      expected: {expected}")
if actual != expected:
    fail("content_hash_sha256 mismatch. PDF has been altered.")
if len(pdf) != manifest["content_bytes"]:
    fail(f"content_bytes mismatch (got {len(pdf)}, expected {manifest['content_bytes']}).")
print("      ✓ hash + byte count match\n")

print("3/4  Verifying Ed25519 signature...")
pub = Ed25519PublicKey.from_public_bytes(base64.b64decode(pubkey_b64))
message = base64.b64decode(manifest["signature_message_canonical"])
sig = base64.b64decode(manifest["signature_ed25519"])
try:
    pub.verify(sig, message)
    print("      ✓ signature verifies against published public key\n")
except InvalidSignature:
    fail("Ed25519 signature did NOT verify.")

print("4/4  Summary...")
print(f"      Document:    PropRaven {manifest['county_name']} Quality Attestation, {manifest['quarter']}")
print(f"      Audit run:   {manifest['audit_run_id']}")
print(f"      Generated:   {manifest['generated_at']}\n")
print("✅ PASS — this attestation is authentic and unaltered.")
