# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-stale-a2a-v1-0-agent-card-as-a-capability-lie-rather-than-a-routing-miss.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-stale-a2a-v1-0-agent-card-as-a-capability-lie-rather-than-a-routing-miss.warrant.json
# Markdown SHA-256:   cb7d142d2f8aeb7b5051669c16d2738192c18f2fac834ce57bbbdcc7221d84a9
# Code AST SHA-256:   bac1d8fc3e45191956526e323aaf2323c25b6121d7ab7d344f24cd9db68ab2f5
# Verified Classes:   StaleAgentCardError, AgentCard, DelegationResult, CardReconciler
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class StaleAgentCardError(RuntimeError):
    """Raised when a peer's cached Agent Card is contradicted by its own failure response."""
    pass


@dataclass
class AgentCard:
    peer_id: str
    version: str
    skills: dict
    capabilities: dict
    fetched_at: float
    ttl_seconds: float = 300.0

    def is_expired(self, now: Optional[float] = None) -> bool:
        return (now or time.time()) - self.fetched_at > self.ttl_seconds

    def contradicts(self, other: "AgentCard") -> bool:
        return self.skills != other.skills or self.capabilities != other.capabilities


@dataclass
class DelegationResult:
    peer_id: str
    state: str  # "completed" | "failed"
    error_field: Optional[str] = None  # e.g. "inputModes", or None if field-agnostic


class CardReconciler:
    def __init__(self, fetch_card, quarantine_seconds: float = 60.0):
        self._fetch_card = fetch_card
        self._quarantine_seconds = quarantine_seconds
        self._quarantined: dict[str, float] = {}
        self._cache: dict[str, AgentCard] = {}

    def resolve(self, peer_id: str) -> AgentCard:
        now = time.time()
        until = self._quarantined.get(peer_id)
        if until is not None and now < until:
            raise StaleAgentCardError(
                f"peer {peer_id} quarantined for capability drift until {until:.0f}"
            )
        card = self._cache.get(peer_id)
        if card is None or card.is_expired(now):
            card = self._fetch_card(peer_id)
            self._cache[peer_id] = card
        return card

    def reconcile_failure(self, result: DelegationResult) -> str:
        """Classify a failed task and, if capability-attesting, quarantine the peer."""
        if result.state != "failed":
            return "no-op"

        cached = self._cache.get(result.peer_id)
        if cached is None:
            raise StaleAgentCardError(
                f"failure from un-cached peer {result.peer_id}; cannot reconcile"
            )

        # Signal A: failure cites a field the card advertised -> capability lie.
        if result.error_field is not None:
            self._quarantined[result.peer_id] = time.time() + self._quarantine_seconds
            raise StaleAgentCardError(
                f"peer {result.peer_id} card contradicted on field "
                f"{result.error_field!r}; quarantined"
            )

        # Signal B is ambiguous: force a re-fetch before trusting the card again.
        fresh = self._fetch_card(result.peer_id)
        if cached.contradicts(fresh):
            self._cache[result.peer_id] = fresh
            self._quarantined[result.peer_id] = time.time() + self._quarantine_seconds
            raise StaleAgentCardError(
                f"peer {result.peer_id} card drifted between cache and re-fetch; "
                f"quarantined and cache refreshed"
            )
        return "transient"
