# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-peer-s-agent-card-as-a-versioned-cache-entry-rather-than-a-live-capability-contract-during-a2a-delegation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-peer-s-agent-card-as-a-versioned-cache-entry-rather-than-a-live-capability-contract-during-a2a-delegation.warrant.json
# Markdown SHA-256:   dd053afa78d6689dc5883e80b4dcf2c981298fd352dbff4e9ebd0bb1ad17e024
# Code AST SHA-256:   c4eb9ccd1ddae210c8cb1caf5b01f081150d8ecb8d6bccf931a104f734d5c4bc
# Verified Classes:   StaleAgentCardError, CapabilityWithdrawalError, CachedCard, DelegationIntent
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional

TTL_CARD_SECONDS = 300  # below observed republication latency; combined with in-band check

class StaleAgentCardError(RuntimeError):
    """Raised when delegation is attempted against a card that no longer matches intent."""
    pass

class CapabilityWithdrawalError(RuntimeError):
    """Raised when a fresh card no longer advertises the intended skill/mode."""
    pass

@dataclass
class CachedCard:
    peer_id: str
    skills: list[str]
    input_modes: list[str]
    fetched_at: float
    supports_structured_rejection: bool = False

@dataclass
class DelegationIntent:
    skill_id: str
    input_mode: str

def delegate(card: CachedCard, intent: DelegationIntent, now: Optional[float] = None) -> dict:
    now = now if now is not None else time.time()
    age = now - card.fetched_at

    # Branch 1: peer advertises clean rejection -> safe to delegate on cache,
    # but still bound by TTL as a backstop.
    if card.supports_structured_rejection and age <= TTL_CARD_SECONDS:
        return {"peer": card.peer_id, "skill": intent.skill_id, "mode": intent.input_mode,
                "validated": "cached+structured_rejection"}

    # Branch 2: no structured rejection OR card is stale -> must revalidate.
    fresh = refetch_card(card.peer_id, cache_bust=True)
    if intent.skill_id not in fresh.skills:
        raise CapabilityWithdrawalError(
            f"peer {card.peer_id} withdrew skill {intent.skill_id} "
            f"(was in card fetched at {card.fetched_at}, absent at {fresh.fetched_at})"
        )
    if intent.input_mode not in fresh.input_modes:
        raise CapabilityWithdrawalError(
            f"peer {card.peer_id} dropped input_mode {intent.input_mode} for {intent.skill_id}"
        )
    if age > TTL_CARD_SECONDS and not card.supports_structured_rejection:
        # Defensive: if we somehow reach here with a stale card and no clean rejection,
        # the delegation is void.
        raise StaleAgentCardError(
            f"card for {card.peer_id} is {age:.0f}s old (TTL {TTL_CARD_SECONDS}s) "
            f"and peer lacks structured rejection; renegotiation required"
        )
    return {"peer": card.peer_id, "skill": intent.skill_id, "mode": intent.input_mode,
            "validated": "revalidated"}

def refetch_card(peer_id: str, cache_bust: bool) -> CachedCard:
    # In production: GET card URL with `?_cb=<nonce>` when cache_bust, honoring Cache-Control.
    raise NotImplementedError("wire to discovery transport")
