# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-cached-agent-card-whose-signing-key-was-rotated-out-of-the-revocation-list-s-freshness-window.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-cached-agent-card-whose-signing-key-was-rotated-out-of-the-revocation-list-s-freshness-window.warrant.json
# Markdown SHA-256:   a91a83b14ab64d9038db90881f2459c5f5b95e4bf63cf0f43d5fa8104e56f4b2
# Code AST SHA-256:   52c75f1266cd30d446f82944ec70e37e9a0977391bd2e8d00f68330b2a5cabe7
# Verified Classes:   StaleRevocationWindowError, CachedCard, CachedRevocationList
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleRevocationWindowError(RuntimeError):
    """Raised when a cached Agent Card is paired with a revocation list
    too old to prove the signing key was not rotated out."""
    pass


@dataclass
class CachedCard:
    agent_id: str
    signing_key_id: str
    fetched_at: float
    ttl: float


@dataclass
class CachedRevocationList:
    revoked_key_ids: frozenset
    fetched_at: float
    ttl: float


def resolve_peer_for_dispatch(
    card: CachedCard,
    rev_list: CachedRevocationList,
    delta_rot: float,
    retry_budget_remaining: float,
    now: float,
) -> str:
    card_age = now - card.fetched_at
    rev_age = now - rev_list.fetched_at

    if card_age > card.ttl:
        raise StaleRevocationWindowError(
            f"card for {card.agent_id} expired (age {card_age:.0f}s > ttl {card.ttl:.0f}s)"
        )

    # The boundary: revocation freshness, not revocation TTL, gates dispatch.
    if rev_age > delta_rot:
        raise StaleRevocationWindowError(
            f"revocation list age {rev_age:.0f}s exceeds rotation-visibility "
            f"window {delta_rot:.0f}s; key status for {card.signing_key_id} "
            f"is indeterminate — force re-fetch before verifying card"
        )

    if card.signing_key_id in rev_list.revoked_key_ids:
        raise StaleRevocationWindowError(
            f"signing key {card.signing_key_id} for {card.agent_id} is revoked"
        )

    effective_window = min(card.ttl, rev_list.ttl) - delta_rot
    if retry_budget_remaining >= effective_window:
        raise StaleRevocationWindowError(
            f"retry budget {retry_budget_remaining:.0f}s outlives effective trust "
            f"window {effective_window:.0f}s; retries could exhaust against a "
            f"peer whose death is invisible until the window closes"
        )

    return f"dispatch_permitted:{card.agent_id}@{card.signing_key_id}"
