# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-discovered-agent-card-after-schema-valid-negotiation-cross-vendor-taskstate-monotonicity-violations-in-a2a-v1-0-task-li.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-discovered-agent-card-after-schema-valid-negotiation-cross-vendor-taskstate-monotonicity-violations-in-a2a-v1-0-task-li.warrant.json
# Markdown SHA-256:   e0319140114d513e1b2dbb6298693bfca2960ae122f81079f56257241ef292ba
# Code AST SHA-256:   8c275333aa5f3d54ab73356482938050911305f994891737a4380bf9609f1101
# Verified Classes:   TaskState, StateMachineIncompatibility, TransitionSet, TaskRecord
# Defensive Guards:   9 fail-closed invariants (zero external deps)

from __future__ import annotations

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


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


TERMINAL: FrozenSet[TaskState] = frozenset(
    {TaskState.COMPLETED, TaskState.FAILED, TaskState.CANCELED}
)


class StateMachineIncompatibility(RuntimeError):
    """Raised when a remote Agent Card's declared task state machine cannot be
    safely folded into the local blocking state machine, or when an observed
    task stream violates the pinned transition contract."""


@dataclass(frozen=True)
class TransitionSet:
    """Declared legal transitions for a task lifecycle, as published in a
    Card's state-machine extension. `quiescent_input_required` marks whether
    input-required may only be exited by a client continuation."""

    edges: FrozenSet[tuple[TaskState, TaskState]]
    quiescent_input_required: bool


# Local (blocking) machine: input-required is quiescent; terminals are sinks.
LOCAL_TRANSITIONS = TransitionSet(
    edges=frozenset(
        {
            (TaskState.SUBMITTED, TaskState.WORKING),
            (TaskState.WORKING, TaskState.INPUT_REQUIRED),
            (TaskState.INPUT_REQUIRED, TaskState.WORKING),  # only via client msg
            (TaskState.WORKING, TaskState.COMPLETED),
            (TaskState.WORKING, TaskState.FAILED),
            (TaskState.SUBMITTED, TaskState.CANCELED),
        }
    ),
    quiescent_input_required=True,
)


@dataclass
class TaskRecord:
    task_id: str
    idempotency_key: str
    pinned: TransitionSet
    state: TaskState = TaskState.SUBMITTED
    history: list[TaskState] = field(default_factory=list)


def negotiate_lifecycle(
    card: dict, local: TransitionSet = LOCAL_TRANSITIONS
) -> TransitionSet:
    """Verify a remote Card's declared state machine is a subset of local.

    Must be called BEFORE the first tasks/send. Refuses the blocking lifecycle
    if the extension is absent or incompatible; does not silently downgrade.
    """
    extensions = card.get("capabilities", {}).get("extensions", [])
    sm = next(
        (e for e in extensions if e.get("type") == "state-machine"), None
    )
    if sm is None:
        raise StateMachineIncompatibility(
            "remote Card declares no state-machine extension; "
            "blocking lifecycle negotiation refused"
        )

    try:
        remote_edges = frozenset(
            (TaskState(e["from"]), TaskState(e["to"])) for e in sm["edges"]
        )
    except (KeyError, ValueError) as exc:
        raise StateMachineIncompatibility(
            f"malformed state-machine extension: {exc!r}"
        ) from exc

    remote = TransitionSet(
        edges=remote_edges,
        quiescent_input_required=bool(sm.get("quiescentInputRequired")),
    )

    if not remote.quiescent_input_required:
        raise StateMachineIncompatibility(
            "remote permits unilateral exit from input-required; "
            "local blocking fold would orphan the task"
        )

    illegal = remote.edges - local.edges
    if illegal:
        raise StateMachineIncompatibility(
            f"remote declares transitions outside local set: {sorted(illegal)}"
        )

    # Reject terminal-state regression explicitly (defense in depth).
    for src, dst in remote.edges:
        if src in TERMINAL and dst not in TERMINAL:
            raise StateMachineIncompatibility(
                f"remote declares terminal regression {src.value}->{dst.value}"
            )

    return remote


def fold_event(record: TaskRecord, new_state: TaskState, client_continued: bool) -> None:
    """Fold one observed task state into the local record under the pinned
    contract. Raises if the stream violates the pinned transition set."""
    if record.state in TERMINAL:
        raise StateMachineIncompatibility(
            f"event after terminal {record.state.value}->{new_state.value} "
            f"for task {record.task_id}"
        )

    edge = (record.state, new_state)
    if edge not in record.pinned.edges:
        raise StateMachineIncompatibility(
            f"undeclared transition {record.state.value}->{new_state.value} "
            f"for task {record.task_id}"
        )

    if record.state is TaskState.INPUT_REQUIRED and not client_continued:
        raise StateMachineIncompatibility(
            f"remote exited input-required without client continuation "
            f"for task {record.task_id} (idempotencyKey={record.idempotency_key})"
        )

    record.history.append(record.state)
    record.state = new_state


def resume(record: TaskRecord, current_card: dict) -> None:
    """Re-verify the pinned contract against the currently-served Card before
    any resume send. Fails closed on drift."""
    live = negotiate_lifecycle(current_card)
    if live.edges != record.pinned.edges:
        raise StateMachineIncompatibility(
            f"remote state machine drifted since task {record.task_id} was "
            f"pinned; resume refused"
        )
