# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-an-a2a-v1-0-agent-card-whose-declared-capabilities-diverge-from-its-task-lifecycle-state-machine.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-an-a2a-v1-0-agent-card-whose-declared-capabilities-diverge-from-its-task-lifecycle-state-machine.warrant.json
# Markdown SHA-256:   af7aae72d033c91023d570b6b58c5ed9af6da86c045c2320f20e696e96decfc1
# Code AST SHA-256:   2805cd34d455e741bf9f6b01165ba487eca2931c1fc65a974389dd0a951f724b
# Verified Classes:   AgentCardDivergenceError, TaskState, AgentCard, ClientFSM
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import Iterable


class AgentCardDivergenceError(RuntimeError):
    """Raised when a peer's Agent Card implies a task-lifecycle state the
    client's FSM cannot handle, before any artifact is committed."""


class TaskState(str, Enum):
    SUBMITTED = "submitted"
    WORKING = "working"
    INPUT_REQUIRED = "input-required"
    COMPLETED = "completed"
    FAILED = "failed"
    CANCELED = "canceled"


@dataclass(frozen=True)
class AgentCard:
    streaming: bool
    push_notifications: bool
    input_modes: tuple[str, ...]
    output_modes: tuple[str, ...]
    skill_id: str


@dataclass
class ClientFSM:
    # States this client can *receive* and act on without losing the task.
    handled_states: set[TaskState] = field(
        default_factory=lambda: {
            TaskState.SUBMITTED,
            TaskState.WORKING,
            TaskState.COMPLETED,
            TaskState.FAILED,
            TaskState.CANCELED,
        }
    )
    # Whether the client has a resume path from INPUT_REQUIRED back to WORKING.
    supports_resume_from_working: bool = False


_STRUCTURED_OUTPUT_PREFIXES = ("application/vnd.",)
_STRUCTURED_OUTPUT_SUFFIXES = ("+json",)


def _implies_mid_stream_input_required(card: AgentCard) -> bool:
    """A2A v1.0 cards do not enumerate reachable states per skill, so we infer:
    streaming + structured output that admits partial/truncated generation
    implies the peer may pause for confirmation mid-stream."""
    if not card.streaming:
        return False
    for mode in card.output_modes:
        if mode.startswith(_STRUCTURED_OUTPUT_PREFIXES) or mode.endswith(
            _STRUCTURED_OUTPUT_SUFFIXES
        ):
            return True
    return False


def _reachable_states(card: AgentCard) -> set[TaskState]:
    states = {
        TaskState.SUBMITTED,
        TaskState.WORKING,
        TaskState.COMPLETED,
        TaskState.FAILED,
        TaskState.CANCELED,
    }
    if _implies_mid_stream_input_required(card):
        states.add(TaskState.INPUT_REQUIRED)
    return states


def validate_card_before_dispatch(
    card: AgentCard,
    fsm: ClientFSM,
    *,
    artifact_already_committed: bool,
) -> None:
    """Gate card acceptance. Must be called before any artifact is streamed
    with append=true, because peer partial state is irreversible once sent."""
    if artifact_already_committed:
        # The invariant is a pre-commit gate; calling it late is a bug.
        raise AgentCardDivergenceError(
            f"card validation for skill {card.skill_id!r} invoked after artifact "
            "commit; orphaned-artifact condition is not recoverable"
        )

    reachable = _reachable_states(card)
    unhandled = reachable - fsm.handled_states

    if unhandled:
        raise AgentCardDivergenceError(
            f"skill {card.skill_id!r} can emit states {sorted(s.value for s in unhandled)} "
            f"that client FSM does not handle; reject and fall back to non-streaming"
        )

    if (
        TaskState.INPUT_REQUIRED in reachable
        and not fsm.supports_resume_from_working
    ):
        raise AgentCardDivergenceError(
            f"skill {card.skill_id!r} may pause mid-stream for input-required "
            f"(streaming={card.streaming}, output_modes={card.output_modes}) "
            f"but client has no resume path and pushNotifications="
            f"{card.push_notifications}; dispatch would orphan artifacts"
        )


def discover_and_dispatch(
    cards: Iterable[AgentCard],
    fsm: ClientFSM,
) -> list[AgentCard]:
    """Returns only cards safe to dispatch against. Rejections are surfaced,
    not silently dropped, so operators can widen the FSM or fall back."""
    dispatchable: list[AgentCard] = []
    for card in cards:
        try:
            validate_card_before_dispatch(
                card, fsm, artifact_already_committed=False
            )
        except AgentCardDivergenceError:
            # Fall back to non-streaming message/send for this peer; do not
            # commit artifacts under the streaming path.
            continue
        dispatchable.append(card)
    return dispatchable
