# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-a2a-agent-card-staleness-when-a-peer-s-declared-capability-set-drifts-across-a-rolling-redeploy.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-a2a-agent-card-staleness-when-a-peer-s-declared-capability-set-drifts-across-a-rolling-redeploy.warrant.json
# Markdown SHA-256:   ed0cf562c5e5cab821a6bce50b7b20e56bccdc35fb2f8065bf5e5abf96ad545b
# Code AST SHA-256:   ca49fcbc34bf1fe01da375f5cb1247d12146293cd0c164a72f54fedfc03ffb7c
# Verified Classes:   StaleAgentCardError, CachedCard, Delegator
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class StaleAgentCardError(RuntimeError):
    """Raised when a cached A2A Agent Card cannot be trusted for dispatch."""
    pass


@dataclass
class CachedCard:
    peer_id: str
    card_bytes: bytes
    fetch_time: float
    declared_version: Optional[str] = None
    declared_completion: str = "sync"  # "sync" | "async"

    def fingerprint(self) -> str:
        return hashlib.sha256(self.card_bytes).hexdigest()


@dataclass
class Delegator:
    cards: dict = field(default_factory=dict)
    max_card_age_s: float = 900.0
    high_consequence: bool = True

    def _fetch_fresh(self, peer_id: str, now: float) -> CachedCard:
        raw = self._rpc_get_card(peer_id)
        return CachedCard(peer_id=peer_id, card_bytes=raw, fetch_time=now)

    def _rpc_get_card(self, peer_id: str) -> bytes:
        raise NotImplementedError

    def dispatch(self, peer_id: str, task: dict, now: float) -> dict:
        cached = self.cards.get(peer_id)
        if cached is None:
            cached = self._fetch_fresh(peer_id, now)
            self.cards[peer_id] = cached

        age = now - cached.fetch_time
        if self.high_consequence or age > self.max_card_age_s:
            fresh = self._fetch_fresh(peer_id, now)
            if fresh.fingerprint() != cached.fingerprint():
                self.cards[peer_id] = fresh
                cached = fresh
            else:
                cached.fetch_time = now

        response = self._rpc_send(peer_id, task)

        if response.get("state") == "rejected":
            msg = response.get("status", {}).get("message", "")
            if "validation failed" in msg or "required field" in msg:
                # Peer's schema view differs from cached view: staleness, not task error.
                fresh = self._fetch_fresh(peer_id, now)
                if fresh.fingerprint() == cached.fingerprint():
                    raise StaleAgentCardError(
                        f"peer {peer_id} rejected task but card fingerprint unchanged; "
                        f"schema drift without card update — cannot bound staleness"
                    )
                self.cards[peer_id] = fresh
                raise StaleAgentCardError(
                    f"peer {peer_id} card drifted mid-session; re-fetch required before redispatch"
                )

        observed_completion = response.get("state")
        if cached.declared_completion == "sync" and observed_completion == "working":
            raise StaleAgentCardError(
                f"peer {peer_id} declared sync completion but returned 'working'; "
                f"completion semantics drifted — re-fetch card and renegotiate"
            )

        return response

    def _rpc_send(self, peer_id: str, task: dict) -> dict:
        raise NotImplementedError
