# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a2a-v1-0-agent-card-discovery-failure-at-the-task-delegation-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a2a-v1-0-agent-card-discovery-failure-at-the-task-delegation-boundary.warrant.json
# Markdown SHA-256:   44772cc450d114523c338b42d4c077d403eb7de3974d34455261746b100d3bd8
# Code AST SHA-256:   b49ece4e107e3c7b49a009ef3b3a05a2b679228e1379c61e069488408a84099b
# Verified Classes:   CardInconsistentError, CardCache
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class CardInconsistentError(RuntimeError):
    """Raised when a cached Agent Card advertises a skill that the RPC surface rejects."""


@dataclass
class CardCache:
    ttl_seconds: float = 300.0
    _entries: dict = field(default_factory=dict)  # agent_url -> (card, fetched_at)

    def get(self, agent_url: str):
        entry = self._entries.get(agent_url)
        if entry is None:
            return None
        card, fetched_at = entry
        if time.monotonic() - fetched_at > self.ttl_seconds:
            del self._entries[agent_url]
            return None
        return card

    def put(self, agent_url: str, card) -> None:
        self._entries[agent_url] = (card, time.monotonic())

    def invalidate(self, agent_url: str) -> None:
        self._entries.pop(agent_url, None)


def delegate(cache: CardCache, agent_url: str, skill_id: str, payload: dict, rpc):
    """Submit a task, distinguishing discovery failure from delegation failure.

    rpc(agent_url, method, params) -> dict, raising RpcError(code, message) on JSON-RPC errors.
    """
    card = cache.get(agent_url)
    if card is None:
        card = rpc(agent_url, "agent/getCard", {})  # discovery surface
        cache.put(agent_url, card)

    advertised = {s.get("id") for s in card.get("skills", [])}
    if skill_id not in advertised:
        # Not a delegation attempt at all: the card does not claim this skill.
        raise CardInconsistentError(
            f"skill {skill_id!r} not advertised by {agent_url}; refusing to delegate"
        )

    try:
        task = rpc(agent_url, "tasks/send", {"skill": skill_id, "input": payload})
    except Exception as exc:
        code = getattr(exc, "code", None)
        if code == -32601:
            # Card advertised the skill, RPC surface does not have it: card/route drift.
            cache.invalidate(agent_url)
            raise CardInconsistentError(
                f"{agent_url} advertised skill {skill_id!r} but returned -32601; "
                f"card invalidated, do not retry against this card"
            ) from exc
        raise

    if task.get("state") == "failed":
        # Task-level failure: payload/handler mismatch, not a discovery problem.
        raise CardInconsistentError(
            f"{agent_url} accepted skill {skill_id!r} but task failed: "
            f"{task.get('error', 'no error detail')}"
        )
    return task
