#!/usr/bin/env python
"""Standalone verifier for GENESIS compliance packs.

Verifies with ZERO trust in GENESIS: recomputes the sha256 hash chain over the
pack's audit entries and checks the Ed25519 signature against a public key —
by default the one published at https://genesishq.net/.well-known/genesis-verify.json,
or one you supply.

Usage:
    python scripts/verify_pack.py pack.json
    python scripts/verify_pack.py pack.json --key <public_key_hex>

Requires: pip install cryptography
"""
from __future__ import annotations

import argparse
import hashlib
import json
import sys
import urllib.request

WELL_KNOWN = "https://genesishq.net/.well-known/genesis-verify.json"


def recompute_chain(entries: list[dict], chain_genesis: str) -> str | None:
    """Returns the recomputed digest, or None if any entry's hash is wrong."""
    prev = chain_genesis
    for e in entries:
        basis = json.dumps({
            "prev": prev, "id": e["id"], "event": e["event"], "at": e["at"],
            "company": e.get("company"), "agent": e.get("agent"),
            "action": e.get("action"), "detail": e["detail"],
        }, sort_keys=True, default=str)
        h = hashlib.sha256(basis.encode()).hexdigest()
        if h != e.get("hash"):
            return None
        prev = h
    return prev


def verify(pack: dict, public_key_hex: str) -> tuple[bool, str]:
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey

    audit = pack.get("audit") or {}
    entries = audit.get("entries") or []
    digest = recompute_chain(entries, audit.get("chain_genesis", ""))
    if digest is None:
        return False, "TAMPERED: an entry's hash does not match its content"
    if digest != audit.get("digest"):
        return False, "TAMPERED: recomputed digest differs from the pack's digest"
    sig = audit.get("signature_ed25519", "")
    try:
        pub = Ed25519PublicKey.from_public_bytes(bytes.fromhex(public_key_hex))
        pub.verify(bytes.fromhex(sig), digest.encode())
    except Exception:
        return False, "TAMPERED: Ed25519 signature does not verify against the key"
    return True, f"VERIFIED: {len(entries)} audit entries intact; signature valid"


def main() -> int:
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument("pack", help="path to the compliance pack JSON")
    ap.add_argument("--key", help="Ed25519 public key hex (default: fetch from "
                                  "genesishq.net/.well-known)")
    args = ap.parse_args()

    with open(args.pack, encoding="utf-8") as f:
        pack = json.load(f)

    key = args.key
    if not key:
        with urllib.request.urlopen(WELL_KNOWN, timeout=20) as r:
            key = json.load(r)["public_key_ed25519"]
        print(f"key: {key[:16]}… (from {WELL_KNOWN})")

    ok, msg = verify(pack, key)
    print(msg)
    return 0 if ok else 1


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