# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-agent-card-during-a2a-v1-0-cross-org-delegation-and-why-does-capability-schema-drift-silently-misroute-tasks.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-agent-card-during-a2a-v1-0-cross-org-delegation-and-why-does-capability-schema-drift-silently-misroute-tasks.warrant.json
# Markdown SHA-256:   2eafb57b6fe16df1be0306c36b07e3574a31a92d1bc5448d3dbcd3d38c1b8f16
# Code AST SHA-256:   6f1acceb79c50b96184871cce8544a2078da8783e9964e51b97c1b6dd1c7f644
# Verified Classes:   CapabilityDriftError, PermanentSchemaError, AgentCard, CardCache
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Any


class CapabilityDriftError(RuntimeError):
    """Raised when a peer's live skill schema disagrees with the cached Agent Card."""


class PermanentSchemaError(RuntimeError):
    """Raised when a peer returns a permanent schema error (-32602 / -32601)."""


@dataclass(frozen=True)
class AgentCard:
    peer_id: str
    version: str
    skills: dict[str, dict[str, Any]]  # skill_id -> {inputSchema, outputSchema, ...}
    etag: str | None = None

    def schema_hash(self, skill_id: str) -> str:
        skill = self.skills.get(skill_id)
        if skill is None:
            raise CapabilityDriftError(
                f"peer {self.peer_id} does not advertise skill {skill_id!r}"
            )
        # Hash only the peer-defined schema fields, not the version string.
        payload = json.dumps(
            {"inputSchema": skill.get("inputSchema"), "outputSchema": skill.get("outputSchema")},
            sort_keys=True,
            separators=(",", ":"),
        )
        return hashlib.sha256(payload.encode()).hexdigest()


class CardCache:
    def __init__(self) -> None:
        self._cards: dict[str, AgentCard] = {}
        self._invalidated: set[str] = set()

    def get(self, peer_id: str) -> AgentCard | None:
        if peer_id in self._invalidated:
            return None
        return self._cards.get(peer_id)

    def put(self, card: AgentCard) -> None:
        self._cards[card.peer_id] = card
        self._invalidated.discard(card.peer_id)

    def invalidate(self, peer_id: str) -> None:
        self._invalidated.add(peer_id)


def dispatch_task(
    cache: CardCache,
    peer_id: str,
    skill_id: str,
    payload: dict[str, Any],
    live_card_fetcher,
    peer_rpc,
    *,
    payload_touches_peer_schema: bool,
) -> dict[str, Any]:
    cached = cache.get(peer_id)
    if cached is None or payload_touches_peer_schema:
        live = live_card_fetcher(peer_id)
        if cached is not None and cached.schema_hash(skill_id) != live.schema_hash(skill_id):
            cache.put(live)
            raise CapabilityDriftError(
                f"schema drift on peer={peer_id} skill={skill_id} "
                f"cached_hash={cached.schema_hash(skill_id)[:12]} "
                f"live_hash={live.schema_hash(skill_id)[:12]}"
            )
        cache.put(live)
        cached = live

    try:
        return peer_rpc(peer_id, "tasks/send", {"skill": skill_id, "params": payload})
    except PermanentSchemaError as exc:
        # A permanent schema error is a card-invalidation signal, not a retryable one.
        cache.invalidate(peer_id)
        live = live_card_fetcher(peer_id)
        if cached.schema_hash(skill_id) != live.schema_hash(skill_id):
            cache.put(live)
            raise CapabilityDriftError(
                f"peer {peer_id} rejected payload with -32602; live schema hash "
                f"{live.schema_hash(skill_id)[:12]} differs from cached "
                f"{cached.schema_hash(skill_id)[:12]}"
            ) from exc
        # Schema unchanged but payload still rejected: caller bug, not drift.
        raise
