# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-cached-agent-card-across-a-remote-task-state-transition-in-a2a-v1-0.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-cached-agent-card-across-a-remote-task-state-transition-in-a2a-v1-0.warrant.json
# Markdown SHA-256:   9d1514ef5e1439c3f86803b68b093edc198e7cf1a2a1287d5736946e3a56a4cd
# Code AST SHA-256:   c30293a6743015945ac14cd3a2d8495ae2443d48fcbe2e0fefb2d061eda148fe
# Verified Classes:   StaleWarrantError, AgentCard, TaskAnchor, A2AClient
# Defensive Guards:   9 fail-closed invariants (zero external deps)

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


class StaleWarrantError(RuntimeError):
    """Raised when a continuation is issued against a cached AgentCard
    or taskId that the live remote no longer honors."""


@dataclass
class AgentCard:
    skills: frozenset
    input_modes: frozenset
    push_notifications: bool
    fetched_at: float


@dataclass
class TaskAnchor:
    task_id: str
    last_observed_state: str
    push_registered: bool
    push_deadline: Optional[float] = None


@dataclass
class A2AClient:
    card_ttl: float = 300.0
    poll_interval: float = 5.0
    cached_card: Optional[AgentCard] = None
    tasks: dict = field(default_factory=dict)

    def _now(self) -> float:
        return time.monotonic()

    def _refetch_card(self) -> AgentCard:
        # In production: GET /.well-known/agent.json and parse.
        raise NotImplementedError

    def _card_is_fresh(self) -> bool:
        if self.cached_card is None:
            return False
        return (self._now() - self.cached_card.fetched_at) <= self.card_ttl

    def send_continuation(self, task_id: str, part_mime: str,
                          want_push: bool) -> str:
        anchor = self.tasks.get(task_id)
        if anchor is None:
            raise StaleWarrantError(
                f"no local anchor for task {task_id}; refusing speculative send"
            )

        # Rule 1: re-validate the card before any continuation.
        if not self._card_is_fresh():
            self.cached_card = self._refetch_card()

        card = self.cached_card
        assert card is not None

        # Rule 2: capability drift check against the live card.
        if part_mime not in card.input_modes:
            self.cached_card = self._refetch_card()
            if part_mime not in self.cached_card.input_modes:
                raise StaleWarrantError(
                    f"input mode {part_mime} not advertised by live card; "
                    f"cached warrant is stale"
                )

        if want_push and not card.push_notifications:
            raise StaleWarrantError(
                "push requested but live card disables pushNotifications; "
                "fall back to tasks/get polling"
            )

        # Rule 3: push liveness bound.
        if anchor.push_registered and anchor.push_deadline is not None:
            if self._now() > anchor.push_deadline:
                raise StaleWarrantError(
                    f"push deadline exceeded for task {task_id}; "
                    f"must poll tasks/get before continuing"
                )

        # Remote call; on -32001 the caller must invalidate.
        response = self._rpc_send(task_id, part_mime, want_push)
        if response.get("error", {}).get("code") == -32001:
            self.tasks.pop(task_id, None)
            self.cached_card = None  # -32001 is evidence of redeploy
            raise StaleWarrantError(
                f"remote returned TaskNotFound for {task_id}; "
                f"card and anchor invalidated"
            )
        return response["result"]["status"]["state"]

    def _rpc_send(self, task_id, part_mime, want_push) -> dict:
        raise NotImplementedError


def negotiate(client: A2AClient, task_id: str, part_mime: str,
              want_push: bool) -> str:
    try:
        return client.send_continuation(task_id, part_mime, want_push)
    except StaleWarrantError as exc:
        # Surface, do not silently retry against the same warrant.
        raise StaleWarrantError(
            f"negotiation halted: {exc}; re-discover and re-anchor required"
        ) from exc
