# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-agent-card-supportedinterfaces-divergence-from-the-live-task-state-machine-after-a-cross-vendor-a2a-v1-0-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-agent-card-supportedinterfaces-divergence-from-the-live-task-state-machine-after-a-cross-vendor-a2a-v1-0-handoff.warrant.json
# Markdown SHA-256:   7280f290db82a66583f1d259a9b8d1bf2ed9c4fde188db0154bde15b9466e28e
# Code AST SHA-256:   e0a305de2e3bbcf63af7eafc1db606205ff45deae21e81bf958042559f32e0a8
# Verified Classes:   A2AStateDivergence, LocalState, AgentCard, RemoteTaskStatus
# 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 Optional


class A2AStateDivergence(RuntimeError):
    """Raised when a client's local task mirror cannot reconcile a remote
    A2A v1.0 Task.status.state with its own transition table, and the
    divergence would collapse a non-terminal remote state into a terminal
    local state without preserving the remote cause."""


class LocalState(str, Enum):
    SUBMITTED = "submitted"
    WORKING = "working"
    INPUT_REQUIRED = "input-required"
    COMPLETED = "completed"
    FAILED = "failed"
    UNKNOWN = "unknown"


TERMINAL = {LocalState.COMPLETED, LocalState.FAILED}
NON_TERMINAL_REMOTE = {"input-required", "auth-required", "working", "submitted"}


@dataclass
class AgentCard:
    protocol_version: str
    streaming: bool
    push_notifications: bool
    state_transition_history: bool
    default_output_modes: list[str] = field(default_factory=list)

    def output_modes_are_attribute_bearing(self) -> bool:
        # FilePart / DataPart may require client-supplied attributes
        # (mimeType, schema, inline vs. reference) that surface as
        # input-required with an untyped Message payload.
        return any(m in {"file", "data"} for m in self.default_output_modes)


@dataclass
class RemoteTaskStatus:
    state: str
    message_code: Optional[str] = None


def reconcile(
    local: LocalState,
    remote: RemoteTaskStatus,
    card: AgentCard,
    poll_deadline_exceeded: bool,
) -> LocalState:
    """Map a remote status onto the local mirror, refusing to collapse a
    non-terminal remote state into a terminal local state unless the
    remote itself is terminal or the poll deadline has passed."""
    if remote.state in NON_TERMINAL_REMOTE:
        if local in TERMINAL and not poll_deadline_exceeded:
            raise A2AStateDivergence(
                f"local mirror is terminal ({local.value}) but remote is "
                f"non-terminal ({remote.state}); refusing to collapse. "
                f"card: history={card.state_transition_history} "
                f"streaming={card.streaming} "
                f"push={card.push_notifications} "
                f"attr_bearing={card.output_modes_are_attribute_bearing()}"
            )
        if remote.state == "input-required":
            if not card.push_notifications and not poll_deadline_exceeded:
                # No push channel: input-required is a dead-end unless we poll.
                return LocalState.INPUT_REQUIRED
            return LocalState.INPUT_REQUIRED
        if remote.state in {"auth-required"}:
            return LocalState.UNKNOWN  # opaque; defer to message, re-discover card
        return LocalState.WORKING

    if remote.state == "completed":
        return LocalState.COMPLETED
    if remote.state in {"failed", "canceled", "rejected"}:
        # Preserve cause; do not let a cause-keyed retry fire on a
        # cause-collision.
        return LocalState.FAILED
    if remote.state == "unknown":
        return LocalState.UNKNOWN

    raise A2AStateDivergence(f"unrecognized remote state: {remote.state!r}")


def resume_after_handoff(
    local: LocalState,
    remote: RemoteTaskStatus,
    card: AgentCard,
    poll_deadline_exceeded: bool,
) -> LocalState:
    # Precondition: a history-off card with attribute-bearing output modes
    # is NOT safe to treat as terminal-only.
    if (
        not card.state_transition_history
        and card.output_modes_are_attribute_bearing()
        and local in TERMINAL
    ):
        raise A2AStateDivergence(
            "history-off + attribute-bearing output modes: terminal-only "
            "inference is invalid; install input-required handler or "
            "re-discover card before resume"
        )
    return reconcile(local, remote, card, poll_deadline_exceeded)
