# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-task-whose-a2a-agent-card-advertises-a-terminal-completed-state-it-can-never-re-enter.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-task-whose-a2a-agent-card-advertises-a-terminal-completed-state-it-can-never-re-enter.warrant.json
# Markdown SHA-256:   96e38fe57fd92cebf78e00c6d0d9d3d63e52b2dd6f9e6d287329e6082f27a867
# Code AST SHA-256:   58d84fb3461ab4cce04100615c5324f8ed47625fb6b1010508a3ce09be41b473
# Verified Classes:   A2AState, IllegalTaskTransition, ReplayDiscrepancy, TaskRecord, TaskRegistry
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from enum import Enum
from dataclasses import dataclass


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


TERMINAL_STATES = frozenset({A2AState.COMPLETED, A2AState.FAILED, A2AState.CANCELED})

# A2A v1.0 allowed transitions. Terminal states have no outgoing edges.
ALLOWED_TRANSITIONS = {
    A2AState.SUBMITTED: {A2AState.WORKING, A2AState.FAILED, A2AState.CANCELED},
    A2AState.WORKING: {A2AState.INPUT_REQUIRED, A2AState.COMPLETED,
                       A2AState.FAILED, A2AState.CANCELED},
    A2AState.INPUT_REQUIRED: {A2AState.WORKING, A2AState.FAILED, A2AState.CANCELED},
    A2AState.COMPLETED: set(),
    A2AState.FAILED: set(),
    A2AState.CANCELED: set(),
}


class IllegalTaskTransition(RuntimeError):
    """Raised when a client attempts a transition the A2A state machine forbids."""


class ReplayDiscrepancy(RuntimeError):
    """Raised when local terminal state disagrees with remote non-terminal state."""


@dataclass
class TaskRecord:
    task_id: str
    state: A2AState
    state_version: int


class TaskRegistry:
    def __init__(self) -> None:
        self._records: dict[str, TaskRecord] = {}

    def observe(self, task_id: str, new_state: A2AState) -> TaskRecord:
        rec = self._records.get(task_id)
        if rec is None:
            self._records[task_id] = TaskRecord(task_id, new_state, 1)
            return self._records[task_id]
        if rec.state in TERMINAL_STATES and new_state not in TERMINAL_STATES:
            raise ReplayDiscrepancy(
                f"task {task_id} locally terminal ({rec.state}) but remote reports "
                f"{new_state}; remote state lost or redeployed"
            )
        if new_state not in ALLOWED_TRANSITIONS[rec.state] and new_state != rec.state:
            raise IllegalTaskTransition(
                f"task {task_id}: {rec.state} -> {new_state} not permitted by A2A v1.0"
            )
        rec.state = new_state
        rec.state_version += 1
        return rec

    def guard_outbound_send(self, task_id: str) -> None:
        """Call before issuing tasks/send against an existing taskId."""
        rec = self._records.get(task_id)
        if rec is None:
            return  # new task, fresh taskId, legal
        if rec.state in TERMINAL_STATES:
            raise IllegalTaskTransition(
                f"refusing tasks/send on {task_id}: local state {rec.state} is absorbing; "
                f"issue a new taskId with referenceTaskIds instead"
            )
        if rec.state != A2AState.INPUT_REQUIRED and rec.state != A2AState.WORKING:
            raise IllegalTaskTransition(
                f"refusing tasks/send on {task_id}: state {rec.state} does not accept input"
            )


def delegate_followup(registry: TaskRegistry, task_id: str, payload: dict) -> dict:
    # Guardrail runs before any side effect or RPC emission.
    registry.guard_outbound_send(task_id)
    return {"jsonrpc": "2.0", "method": "tasks/send",
            "params": {"id": task_id, "message": payload}}
