# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-validly-signed-a2a-v1-0-agent-card-the-revocation-freshness-gap-in-federated-discovery.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-validly-signed-a2a-v1-0-agent-card-the-revocation-freshness-gap-in-federated-discovery.warrant.json
# Markdown SHA-256:   a542d7ec0ad14b58f6ed2d7b17d7f95a839fbbbd4a3262f30a23b5f2c1e9d1d7
# Code AST SHA-256:   2a7c4f77b9951827b4d62e0ae225ae2856a336fa0daccadf86e9265981d491ff
# Verified Classes:   RevocationFreshnessError, CardState, RevocationState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class RevocationFreshnessError(RuntimeError):
    """Raised when revocation state cannot be shown to be causally later than card state."""


@dataclass(frozen=True)
class CardState:
    identity: str
    cached_at: float
    signature_verified: bool


@dataclass(frozen=True)
class RevocationState:
    fetched_at: float
    next_update: float
    revoked_identities: frozenset


def verify_card_authorization(
    card: CardState,
    revocation: RevocationState,
    *,
    now: float | None = None,
    clock_skew: float = 30.0,
) -> bool:
    if now is None:
        now = time.time()

    if not card.signature_verified:
        raise RevocationFreshnessError(
            f"card for {card.identity!r} failed signature verification; "
            "cannot proceed to authorization check"
        )

    if revocation.next_update + clock_skew < now:
        raise RevocationFreshnessError(
            f"revocation list stale: nextUpdate={revocation.next_update:.0f} "
            f"now={now:.0f}; refusing to make an authorization decision"
        )

    # The core invariant: revocation state must be causally later than card state.
    if revocation.fetched_at <= card.cached_at:
        raise RevocationFreshnessError(
            f"indeterminate authorization for {card.identity!r}: "
            f"revocation fetched_at={revocation.fetched_at:.0f} is not later than "
            f"card cached_at={card.cached_at:.0f}; a synchronous refresh is required "
            "before any accept decision can be made"
        )

    return card.identity not in revocation.revoked_identities


def discover_peer(
    card: CardState,
    fetch_revocation,
    *,
    now: float | None = None,
) -> bool:
    if now is None:
        now = time.time()

    revocation = fetch_revocation()
    try:
        return verify_card_authorization(card, revocation, now=now)
    except RevocationFreshnessError:
        # Fail closed on the indeterminate branch: force one synchronous refresh.
        refreshed = fetch_revocation(force=True)
        return verify_card_authorization(card, refreshed, now=now)
