# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-verified-a2a-agent-card-as-stale-the-moment-the-remote-vendor-rotates-its-signing-key-mid-handshake.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-verified-a2a-agent-card-as-stale-the-moment-the-remote-vendor-rotates-its-signing-key-mid-handshake.warrant.json
# Markdown SHA-256:   63c0e535df5cdeae57887054829afc38e25a3c573dc64e7b87d66724c5b8bf5c
# Code AST SHA-256:   8ecf4555cd0338eb893bbda5d2d4569a29cadddbb64a1e12a3f8b13a6a958980
# Verified Classes:   AgentCardStaleError, CardObservation, CardBindingGuard
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class AgentCardStaleError(RuntimeError):
    """Raised when a verified Agent Card cannot be trusted for capability binding."""


@dataclass
class CardObservation:
    kid: str
    issued_at: float          # from signatures[0].protected.iat
    streaming: bool
    skills: frozenset[str]
    fetched_at: float
    etag_304: bool


class CardBindingGuard:
    def __init__(self, max_card_age_s: float = 300.0):
        self.max_card_age_s = max_card_age_s

    def assert_bindable(
        self,
        card: CardObservation,
        current_jwks_kids: set[str],
        retired_kids: set[str],
        now: float | None = None,
    ) -> None:
        now = now if now is not None else time.time()

        if card.kid in retired_kids:
            raise AgentCardStaleError(
                f"kid {card.kid!r} is retired in vendor key-status; card signature "
                f"is authentic but no longer authoritative for capabilities"
            )

        if card.kid not in current_jwks_kids:
            raise AgentCardStaleError(
                f"kid {card.kid!r} absent from current JWKS; key rotated and pruned, "
                f"cached card cannot be re-verified against live keys"
            )

        age = now - card.issued_at
        if age > self.max_card_age_s:
            raise AgentCardStaleError(
                f"card iat age {age:.0f}s exceeds max_card_age {self.max_card_age_s:.0f}s; "
                f"capability state unbound from signing-key state"
            )

        if card.etag_304 and age > self.max_card_age_s * 0.5:
            raise AgentCardStaleError(
                "conditional GET returned 304 but card is past half-TTL; "
                "ETag attests body continuity, not capability continuity — "
                "force unconditional re-fetch before binding"
            )

    def bind_streaming(self, card: CardObservation, jwks: set[str], retired: set[str]) -> None:
        self.assert_bindable(card, jwks, retired)
        if not card.streaming:
            raise AgentCardStaleError(
                "card does not advertise streaming; handshake must use synchronous tasks/send"
            )
