# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-an-a2a-v1-0-agent-card-as-a-stale-capability-claim-rather-than-a-live-contract.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-an-a2a-v1-0-agent-card-as-a-stale-capability-claim-rather-than-a-live-contract.warrant.json
# Markdown SHA-256:   b5fd4a34df53c61235651b049f48d3dc00d615ae1b50802f588ae180f6c44a31
# Code AST SHA-256:   475107b2896816a8c55ef7a01c7ee925c2650953fa5d7f24885a30112d1fe1c0
# Verified Classes:   StaleAgentCardError, AgentCard, CardCache
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class StaleAgentCardError(RuntimeError):
    """Raised when a task failure is explained by a card that no longer matches the peer."""
    pass


@dataclass
class AgentCard:
    url: str
    version: str
    skills: dict  # skillId -> {"inputModes": [...], "outputModes": [...]}
    capabilities: dict
    fetched_at: float = field(default_factory=time.time)


@dataclass
class CardCache:
    by_url: dict = field(default_factory=dict)

    def get(self, url: str) -> Optional[AgentCard]:
        return self.by_url.get(url)

    def put(self, card: AgentCard) -> None:
        # Key by card.url, NOT by discovery origin: a gateway may front many backends.
        self.by_url[card.url] = card


# Error classes that a stale card can produce. Anything else is a genuine peer fault.
STALENESS_SIGNATURES = frozenset({
    "invalid-params",       # -32602: unknown skillId
    "method-not-found",     # -32601: removed method
    "unsupported-modality", # inputMode dropped from card
    "auth-scheme-mismatch", # securitySchemes rotated
})


def revalidate_before_blame(
    cache: CardCache,
    card_url: str,
    observed_error_class: str,
    fetch_card,  # callable(url) -> AgentCard
) -> AgentCard:
    """
    Null-hypothesis guard: before attributing a cross-vendor failure to the peer,
    the client, or the transport, prove the cached card still matches the peer.
    Runs BEFORE the error classifier and BEFORE peer-health updates.
    """
    if observed_error_class not in STALENESS_SIGNATURES:
        cached = cache.get(card_url)
        if cached is None:
            raise StaleAgentCardError(
                f"no cached card for {card_url}; cannot attribute non-staleness error"
            )
        return cached

    cached = cache.get(card_url)
    fresh = fetch_card(card_url)

    if cached is None:
        cache.put(fresh)
        return fresh

    # Version reuse across breaking builds is legal in A2A v1.0; diff the body, not the version.
    if fresh.skills == cached.skills and fresh.capabilities == cached.capabilities:
        # Card unchanged but error signature matches staleness: the peer is lying about its card,
        # or the failure is genuinely elsewhere. Escalate rather than retry.
        raise StaleAgentCardError(
            f"peer at {card_url} returned {observed_error_class} but card is unchanged; "
            f"card is not a reliable capability source for this peer"
        )

    cache.put(fresh)
    return fresh


def issue_task(cache: CardCache, card_url: str, skill_id: str, fetch_card, send_task):
    card = cache.get(card_url)
    if card is None:
        card = fetch_card(card_url)
        cache.put(card)

    if skill_id not in card.skills:
        # Do not send a task against a skill the card does not claim. Refetch first.
        card = fetch_card(card_url)
        cache.put(card)
        if skill_id not in card.skills:
            raise StaleAgentCardError(
                f"skill {skill_id!r} absent from fresh card at {card_url}"
            )

    try:
        return send_task(card, skill_id)
    except Exception as exc:
        err_class = getattr(exc, "error_class", "unknown")
        fresh = revalidate_before_blame(cache, card_url, err_class, fetch_card)
        # Exactly one retry against the revalidated card; never loop.
        return send_task(fresh, skill_id)
