# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-peer-warrant-when-its-own-trust-domain-has-not-yet-rotated-the-a2a-verification-key.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-peer-warrant-when-its-own-trust-domain-has-not-yet-rotated-the-a2a-verification-key.warrant.json
# Markdown SHA-256:   174aa386457f60405aba0432b2820ad61f9c9b48eefccf2d1792763e9ea6fbd1
# Code AST SHA-256:   ea20dda6fda3332c77cbf398b22411c8609f5fea798c37a0f2c1d615c4482647
# Verified Classes:   RevokedWarrantAccepted, KeyRecord, Warrant, A2AVerifier
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class RevokedWarrantAccepted(RuntimeError):
    """Raised when a warrant is honored despite revocation due to stale key lineage."""
    pass


@dataclass
class KeyRecord:
    key_id: str
    epoch: int
    fetched_at: float


@dataclass
class Warrant:
    issuer: str
    issuer_key_id: str
    issuer_epoch: int
    subject: str


class A2AVerifier:
    def __init__(self, key_cache_ttl: float = 300.0, crl_ttl: float = 60.0):
        self.key_cache_ttl = key_cache_ttl
        self.crl_ttl = crl_ttl
        self._keys: dict[str, KeyRecord] = {}
        self._crl: dict[str, tuple[set[str], KeyRecord, float]] = {}
        self._current_epoch: dict[str, int] = {}

    def _fetch_key(self, issuer: str, key_id: str, epoch: int) -> KeyRecord:
        rec = KeyRecord(key_id=key_id, epoch=epoch, fetched_at=time.time())
        self._keys[f"{issuer}/{key_id}"] = rec
        return rec

    def _fetch_crl(self, issuer: str, signing_key_id: str, signing_epoch: int):
        crl_signer = self._fetch_key(issuer, signing_key_id, signing_epoch)
        revoked = {f"{issuer}/w-revoked"}  # simplified: this warrant id is revoked
        self._crl[issuer] = (revoked, crl_signer, time.time())
        return self._crl[issuer]

    def verify(self, warrant: Warrant, now: float | None = None) -> bool:
        now = now or time.time()

        # 1. Epoch gate: if issuer has rotated past the warrant's epoch, force refresh.
        current_epoch = self._current_epoch.get(warrant.issuer, warrant.issuer_epoch)
        if warrant.issuer_epoch < current_epoch:
            # warrant signed in a superseded epoch -> cannot be current-and-authorized
            raise RevokedWarrantAccepted(
                f"warrant {warrant.subject} from {warrant.issuer} "
                f"epoch {warrant.issuer_epoch} < current {current_epoch}"
            )

        # 2. Resolve key with on-demand fetch (key-on-miss, not lazy TTL).
        key = self._keys.get(f"{warrant.issuer}/{warrant.issuer_key_id}")
        if key is None or (now - key.fetched_at) > self.key_cache_ttl:
            key = self._fetch_key(
                warrant.issuer, warrant.issuer_key_id, warrant.issuer_epoch
            )

        # 3. CRL must be verifiable with a key at least as fresh as the warrant lineage.
        crl_entry = self._crl.get(warrant.issuer)
        crl_stale = crl_entry is None or (now - crl_entry[2]) > self.crl_ttl
        if crl_stale:
            crl_entry = self._fetch_crl(
                warrant.issuer, warrant.issuer_key_id, warrant.issuer_epoch
            )
        revoked, crl_signer, _ = crl_entry

        # Fail-closed: CRL signer epoch must be >= warrant epoch, else we cannot
        # trust the CRL as covering this warrant's lineage.
        if crl_signer.epoch < warrant.issuer_epoch:
            raise RevokedWarrantAccepted(
                f"CRL for {warrant.issuer} signed at epoch {crl_signer.epoch} "
                f"cannot bound warrant at epoch {warrant.issuer_epoch}"
            )

        if f"{warrant.issuer}/w-revoked" in revoked:
            raise RevokedWarrantAccepted(
                f"warrant {warrant.subject} revoked by {warrant.issuer}"
            )
        return True


def handle_peer_handoff(verifier: A2AVerifier, warrant: Warrant) -> str:
    try:
        verifier.verify(warrant)
        return "accepted"
    except RevokedWarrantAccepted as exc:
        # loud, bounded denial -- never silently honor
        raise RevokedWarrantAccepted(f"handoff refused: {exc}") from exc
