# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-ignore-a-valid-a2a-task-state-transition-after-the-card-s-defaultinputmodes-drift-from-the-negotiated-task-schema.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-ignore-a-valid-a2a-task-state-transition-after-the-card-s-defaultinputmodes-drift-from-the-negotiated-task-schema.warrant.json
# Markdown SHA-256:   0d8ab7e9e9b1cca35e63390433d6b5215fc099434ebca4abd7a7afdabbcae3a7
# Code AST SHA-256:   2c8e781b0cff6600af0b919cafe4bba52d52b382aa7bec347792b781ff2f72c5
# Verified Classes:   CardDriftTransitionError, BoundSchema, TaskRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Literal

TaskState = Literal["submitted", "working", "input-required", "completed", "failed", "canceled"]

LEGAL_TRANSITIONS: dict[TaskState, set[TaskState]] = {
    "submitted": {"working", "failed", "canceled"},
    "working": {"input-required", "completed", "failed", "canceled"},
    "input-required": {"working", "failed", "canceled"},
    "completed": set(),
    "failed": set(),
    "canceled": set(),
}


class CardDriftTransitionError(RuntimeError):
    """Raised when a status event's transition is legal under the live card
    but not under the task's frozen bound schema, or vice versa."""


@dataclass(frozen=True)
class BoundSchema:
    input_modes: frozenset[str]
    output_modes: frozenset[str]
    revision: str

    @classmethod
    def from_card(cls, card: dict) -> "BoundSchema":
        modes = frozenset(card.get("defaultInputModes", []))
        outs = frozenset(card.get("defaultOutputModes", []))
        rev = hashlib.sha256(
            repr(sorted(modes) + sorted(outs)).encode()
        ).hexdigest()[:12]
        return cls(input_modes=modes, output_modes=outs, revision=rev)


@dataclass
class TaskRecord:
    task_id: str
    bound: BoundSchema
    state: TaskState = "submitted"
    history: list[tuple[TaskState, TaskState]] = field(default_factory=list)


def apply_status_event(
    task: TaskRecord,
    new_state: TaskState,
    prompt_modality: str | None = None,
    event_card_revision: str | None = None,
) -> TaskRecord:
    # Guard 1: transition must be legal under the FROZEN bound schema.
    if new_state not in LEGAL_TRANSITIONS[task.state]:
        raise CardDriftTransitionError(
            f"illegal transition {task.state}->{new_state} for task {task.task_id}"
        )

    # Guard 2: input-required must request a modality the task was bound with.
    if new_state == "input-required":
        if prompt_modality is None:
            raise CardDriftTransitionError(
                f"input-required on {task.task_id} carries no prompt modality"
            )
        if prompt_modality not in task.bound.input_modes:
            raise CardDriftTransitionError(
                f"input-required on {task.task_id} requests modality "
                f"{prompt_modality!r} not in bound schema {sorted(task.bound.input_modes)} "
                f"(revision {task.bound.revision}); server violated bind contract"
            )

    # Guard 3: if the event carries a card revision, it MUST match the bound one.
    if event_card_revision is not None and event_card_revision != task.bound.revision:
        raise CardDriftTransitionError(
            f"status event for {task.task_id} produced under card revision "
            f"{event_card_revision}, task bound under {task.bound.revision}; "
            f"refusing to reconcile across revisions"
        )

    task.history.append((task.state, new_state))
    task.state = new_state
    return task
