#!/usr/bin/env python3
"""Clean-room verifier for a governance authorization proof. ZERO CAIN imports.

    python3 verifier.py <AUTHORIZATION_PROOF.json>

Independently recomputes the canonical action digest, confirms the authorization is bound to the exact
action and resource scope, checks policy/epoch/trust binding, temporal validity, quorum decision and
the Ed25519 signature. Exit 0 = verified, 1 = failure.
"""
from __future__ import annotations

import base64
import hashlib
import json
import sys

try:
    from cryptography.exceptions import InvalidSignature
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
except Exception:  # pragma: no cover
    Ed25519PublicKey = None


def canon(d) -> bytes:
    return json.dumps(d, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")


def sha(d) -> str:
    return hashlib.sha256(canon(d)).hexdigest()


def verify(proof: dict) -> list:
    problems = []
    action = proof.get("action", {})
    auth = proof.get("authorization", {})
    quorum = proof.get("quorum", {})
    ctx = proof.get("context", {})

    action_digest = sha(action)
    if action_digest != auth.get("action_digest"):
        problems.append("authorization not bound to this action")

    if action.get("resource") not in set(auth.get("resource_scope", [])):
        problems.append("action resource outside authorized scope")

    if auth.get("capability") != action.get("capability"):
        problems.append("capability mismatch")

    if auth.get("policy_version") != ctx.get("current_policy_version"):
        problems.append("policy version invalidated")
    if auth.get("governance_epoch") != ctx.get("current_governance_epoch"):
        problems.append("governance epoch invalid")
    if auth.get("trust_epoch") != ctx.get("current_trust_epoch") or action.get("trust_epoch") != ctx.get("current_trust_epoch"):
        problems.append("trust epoch stale")

    now = ctx.get("now", 0)
    if not (auth.get("issued_at", 0) <= now <= auth.get("expires_at", 0)) or action.get("expires_at", 0) < now:
        problems.append("authorization not temporally valid")

    if sha(quorum) != auth.get("quorum_decision_hash"):
        problems.append("quorum decision mismatch")
    if not quorum.get("valid") or len(quorum.get("signers", [])) < quorum.get("threshold", 1):
        problems.append("quorum insufficient")

    body = {k: v for k, v in auth.items() if k != "signature_b64"}
    pub = ctx.get("agent_public_key_b64", "")
    sig = auth.get("signature_b64", "")
    if Ed25519PublicKey is None:
        problems.append("cryptography unavailable")
    elif pub and sig:
        try:
            Ed25519PublicKey.from_public_bytes(base64.b64decode(pub)).verify(base64.b64decode(sig), canon(body))
        except (InvalidSignature, ValueError):
            problems.append("authorization signature invalid")
    else:
        problems.append("missing public key or signature")
    return problems


def main(argv: list) -> int:
    if len(argv) < 2:
        print("usage: verifier.py <AUTHORIZATION_PROOF.json>", file=sys.stderr); return 2
    proof = json.load(open(argv[1], encoding="utf-8"))
    problems = verify(proof)
    if problems:
        print("GOVKERNEL PROOF FAILED:")
        for p in problems:
            print("  -", p)
        return 1
    print("GOVKERNEL AUTHORIZATION PROOF VERIFIED (independent recomputation)")
    return 0


if __name__ == "__main__":
    raise SystemExit(main(sys.argv))
