# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-an-a2a-task-handoff-when-input-required-and-auth-required-states-race-across-vendors.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-an-a2a-task-handoff-when-input-required-and-auth-required-states-race-across-vendors.warrant.json
# Markdown SHA-256:   cecc1cc8b67cd717d177f714cf25900859481ad9cb6445e2a2e617e82a5e5729
# Code AST SHA-256:   137ad198f2d664defd4975b6ce15ef176a52456b415ace253666a23244925029
# Verified Classes:   InterruptibleState, TaskHandoffError, AgentCard, TaskSnapshot
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class InterruptibleState(Enum):
    INPUT_REQUIRED = "input-required"
    AUTH_REQUIRED = "auth-required"


class TaskHandoffError(RuntimeError):
    """Raised when an A2A task cannot be safely resumed across a vendor boundary."""


@dataclass(frozen=True)
class AgentCard:
    vendor: str
    state_transition_history: bool
    security_scheme_types: frozenset


@dataclass(frozen=True)
class TaskSnapshot:
    task_id: str
    state: InterruptibleState
    challenge_scope: Optional[str]
    terminal: bool


def assert_resumable(
    client_observed: TaskSnapshot,
    remote_current: TaskSnapshot,
    remote_card: AgentCard,
    transition_log: Optional[list],
) -> None:
    """
    Enforce the cross-vendor interruptible-state resume invariant.

    Raises TaskHandoffError if the client cannot prove that the remote's
    current interruptible state matches the state the client last observed,
    or if the remote's card does not permit transition provenance to be
    reconstructed.
    """
    if client_observed.task_id != remote_current.task_id:
        raise TaskHandoffError(
            f"task id mismatch: client holds {client_observed.task_id!r}, "
            f"remote reports {remote_current.task_id!r}"
        )

    if remote_current.terminal:
        raise TaskHandoffError(
            f"remote task {remote_current.task_id!r} is terminal; "
            f"resume would burn the id and collide with the idempotency window"
        )

    same_state = client_observed.state == remote_current.state
    same_scope = client_observed.challenge_scope == remote_current.challenge_scope

    if same_state and same_scope:
        return

    if not remote_card.state_transition_history:
        raise TaskHandoffError(
            f"vendor {remote_card.vendor!r} coerced interruptible state "
            f"{client_observed.state.value!r} -> {remote_current.state.value!r} "
            f"without advertising stateTransitionHistory; resume is unprovable"
        )

    if transition_log is None:
        raise TaskHandoffError(
            f"vendor {remote_card.vendor!r} advertises transition history but "
            f"client did not fetch the log between observations"
        )

    edge_present = any(
        entry.get("from") == client_observed.state.value
        and entry.get("to") == remote_current.state.value
        and entry.get("challenge_scope") == remote_current.challenge_scope
        for entry in transition_log
    )
    if not edge_present:
        raise TaskHandoffError(
            f"transition {client_observed.state.value!r} -> "
            f"{remote_current.state.value!r} with scope "
            f"{remote_current.challenge_scope!r} is not attested in the log; "
            f"refusing resume and requiring re-delegation under a new task_id "
            f"with metadata.parent_task={client_observed.task_id!r}"
        )


def resume_or_redelegate(
    client_observed: TaskSnapshot,
    remote_current: TaskSnapshot,
    remote_card: AgentCard,
    transition_log: Optional[list],
) -> str:
    """Returns 'resume' or 'redelegate' based on the invariant."""
    try:
        assert_resumable(client_observed, remote_current, remote_card, transition_log)
        return "resume"
    except TaskHandoffError:
        return "redelegate"
