# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-peer-s-agent-card-at-discovery-but-then-fail-the-task-lifecycle-handshake-mid-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-peer-s-agent-card-at-discovery-but-then-fail-the-task-lifecycle-handshake-mid-execution.warrant.json
# Markdown SHA-256:   848607096571b9895f28513d49b4c84356c269abd546a0e1afab76ed77c50dac
# Code AST SHA-256:   34b034e53130047a11d599192ee475516080aa5a9656e90dd792e0b756a98a90
# Verified Classes:   A2AProtocolFault, TaskState, AgentCard, StatusEvent
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class A2AProtocolFault(RuntimeError):
    """Raised when a remote agent's wire behavior contradicts its Agent Card."""


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


# The A2A v1.0 message-part schema is closed. A conformant client must
# accept every kind here, regardless of what the card's inputModes says.
CLOSED_PART_KINDS = frozenset({"text", "file", "data"})


@dataclass
class AgentCard:
    protocol_version: str
    streaming: bool
    state_transition_history: bool
    input_modes: list[str]
    output_modes: list[str]


@dataclass
class StatusEvent:
    state: TaskState
    part_kinds: frozenset[str] = field(default_factory=frozenset)


def reconcile_stream_against_history(
    card: AgentCard,
    stream_events: list[StatusEvent],
    history_states: list[TaskState],
) -> None:
    """Enforce the card-to-wire invariant before trusting a remote task.

    Two independent checks, both required:
      1. Every inbound part kind is in the closed message schema. The card's
         outputModes do NOT bound emittable kinds; keying a deserializer off
         it is the classic cross-vendor stall.
      2. If state_transition_history is declared true, the tasks/get history
         must contain every state the live stream emitted, in order. A lossy
         history makes resume-after-reconnect reconstruct a false lifecycle.
    """
    for event in stream_events:
        unknown = event.part_kinds - CLOSED_PART_KINDS
        if unknown:
            raise A2AProtocolFault(
                f"remote emitted part kinds {sorted(unknown)} not in closed "
                f"message schema; client parser would stall the task"
            )

    if card.state_transition_history:
        stream_seq = [e.state for e in stream_events]
        if history_states != stream_seq:
            raise A2AProtocolFault(
                f"declared stateTransitionHistory=true but tasks/get history "
                f"{[s.value for s in history_states]} diverges from live "
                f"stream {[s.value for s in stream_seq]}; resume would "
                f"reconstruct a false lifecycle"
            )


def drive_task(card: AgentCard, stream_events: list[StatusEvent],
               history_states: list[TaskState]) -> Optional[TaskState]:
    reconcile_stream_against_history(card, stream_events, history_states)
    # Only after the invariant holds may the client trust the card's
    # declared capabilities for routing subsequent tasks.
    return stream_events[-1].state if stream_events else None
