# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-a2a-agent-card-when-the-revocation-propagates-faster-than-the-card-signature-verification-cache.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-a2a-agent-card-when-the-revocation-propagates-faster-than-the-card-signature-verification-cache.warrant.json
# Markdown SHA-256:   b03911e08b434074fc9d363fad6eeb0d2ea45a3b39984997e188e3351d6b2e60
# Code AST SHA-256:   dff8e209c1cf578ba22d500cbaf3dfd9af2093892fe67f178ac15fa8c216b9a7
# Verified Classes:   RevocationStateIndeterminate, RevocationList, CachedVerification, RelyingPartyTrustGate
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

import time
from dataclasses import dataclass
from typing import Optional


class RevocationStateIndeterminate(RuntimeError):
    """Raised when the relying party cannot establish current revocation state.

    This is distinct from a signature failure. The card's signature may be
    perfectly valid; what is unknown is whether the issuing org has revoked
    the agent's authority. Cross-org calls MUST fail closed in this state.
    """


@dataclass(frozen=True)
class RevocationList:
    sequence: int
    next_update: float          # unix seconds
    revoked_kids: frozenset[str]
    signature_verified: bool


@dataclass(frozen=True)
class CachedVerification:
    kid: str
    signature_valid: bool
    verified_at: float


class RelyingPartyTrustGate:
    def __init__(self, staleness_budget_s: float = 30.0) -> None:
        self._sig_cache: dict[str, CachedVerification] = {}
        self._revocation: Optional[RevocationList] = None
        self._staleness_budget = staleness_budget_s

    def _signature_ok(self, kid: str, now: float) -> bool:
        # Signature verification is a pure function of immutable card bytes
        # and the issuer key identified by kid. Caching it is sound.
        cached = self._sig_cache.get(kid)
        if cached is None:
            return False
        return cached.signature_valid

    def _revocation_fresh(self, now: float) -> bool:
        rl = self._revocation
        if rl is None or not rl.signature_verified:
            return False
        # Fresh means: the list claims currency through now, and we fetched
        # it within our staleness budget. Both must hold.
        return now <= rl.next_update and (now - rl.next_update) <= self._staleness_budget

    def authorize_cross_org(self, kid: str, now: Optional[float] = None) -> bool:
        now = time.time() if now is None else now

        if not self._signature_ok(kid, now):
            # Signature decision is definitive and cacheable.
            return False

        if not self._revocation_fresh(now):
            # We know the signature is good, but we do NOT know whether the
            # agent is revoked. Do not collapse this into True or False.
            raise RevocationStateIndeterminate(
                f"cannot authorize kid={kid!r} at t={now}: revocation list "
                f"is missing, unsigned, or stale beyond "
                f"{self._staleness_budget}s; failing closed for cross-org call"
            )

        assert self._revocation is not None
        # Membership is keyed by kid, which is present in the request path.
        # We never need to re-parse the card body to make this decision.
        if kid in self._revocation.revoked_kids:
            return False

        return True
