# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-cached-agent-card-past-a-signing-key-rotation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-cached-agent-card-past-a-signing-key-rotation.warrant.json
# Markdown SHA-256:   1a95596e5d2d93ee0d1d2d36775eb54f2eb7998421fe485a64b09cc4fdcc4ff1
# Code AST SHA-256:   1f8d70769470f0abd831ed6b0551f13f23a15980f66a3b2c597cd069acbf0245
# Verified Classes:   StaleAgentCardError, KeyLivenessError, CachedCard, LivePeerState
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass, field


class StaleAgentCardError(RuntimeError):
    """Raised when a cached Agent Card authorizes a capability the peer has revoked."""


class KeyLivenessError(RuntimeError):
    """Raised when the card's signing kid is no longer present in the peer's JWKS."""


@dataclass
class CachedCard:
    agent_id: str
    kid: str
    jwks_snapshot_hash: str
    capabilities: dict
    security_schemes: dict
    cached_at: float
    ttl_seconds: float = 86400.0


@dataclass
class LivePeerState:
    agent_id: str
    current_kids: set
    current_capabilities: dict
    current_security_schemes: dict


# Capabilities that, when exercised, cause the orchestrator to block on a
# peer-controlled channel. These may never be authorized by a stale cache.
BLOCKING_CAPABILITIES = {"pushNotifications", "stateTransitionHistory", "streaming"}


def assert_card_authorizes_handoff(
    card: CachedCard,
    live: LivePeerState,
    requested_capabilities: set,
    now: float | None = None,
) -> None:
    now = now if now is not None else time.time()

    # (1) TTL gate — cheapest, catches the long-tail case.
    if now - card.cached_at > card.ttl_seconds:
        raise StaleAgentCardError(
            f"card for {card.agent_id} expired "
            f"({now - card.cached_at:.0f}s > ttl {card.ttl_seconds:.0f}s)"
        )

    # (2) Key-liveness gate — the invariant most implementations drop.
    if card.kid not in live.current_kids:
        raise KeyLivenessError(
            f"signing kid {card.kid!r} for {card.agent_id} is absent from current JWKS; "
            f"cached card is a valid artifact of a retired trust state"
        )

    # (3) Capability-drift gate — only for capabilities that change request shape.
    for cap in requested_capabilities:
        if cap not in BLOCKING_CAPABILITIES:
            continue
        if not live.current_capabilities.get(cap, False):
            raise StaleAgentCardError(
                f"requested capability {cap!r} for {card.agent_id} was advertised in "
                f"cached card (kid={card.kid}) but is absent from the live card; "
                f"refusing handoff that would block on a peer-controlled channel"
            )

    # (4) Security-scheme drift gate — catches mid-task 401s before they happen.
    if card.security_schemes != live.current_security_schemes:
        raise StaleAgentCardError(
            f"securitySchemes for {card.agent_id} drifted since card was cached; "
            f"credentials minted under cached scheme would fail mid-task"
        )


def negotiate_handoff(
    card: CachedCard,
    live: LivePeerState,
    requested_capabilities: set,
) -> dict:
    try:
        assert_card_authorizes_handoff(card, live, requested_capabilities)
    except (StaleAgentCardError, KeyLivenessError) as exc:
        # Force re-fetch + re-verify, then retry once against the fresh card.
        raise StaleAgentCardError(
            f"handoff to {card.agent_id} blocked; re-fetch required: {exc}"
        ) from exc
    return {
        "agent_id": card.agent_id,
        "kid": card.kid,
        "capabilities": {c: True for c in requested_capabilities},
        "epoch": hashlib.sha256(
            f"{card.kid}:{card.jwks_snapshot_hash}".encode()
        ).hexdigest()[:16],
    }
