# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-an-a2a-task-resume-when-the-remote-agent-card-s-statetransitionhistory-capability-silently-flips-between-dis.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-an-a2a-task-resume-when-the-remote-agent-card-s-statetransitionhistory-capability-silently-flips-between-dis.warrant.json
# Markdown SHA-256:   7e8f89b623b98ec0868fbd874a84bf629b2194c2ae36c0a81ee9e21115c0dbc9
# Code AST SHA-256:   47822d7c975f177572ecb8e170e581b90160d907528edf1cf026a97dc7be0d60
# Verified Classes:   ResumeInvariantViolated, TaskState, Checkpoint, RemoteCard, ResumeResponse
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from enum import IntEnum
from typing import Optional


class ResumeInvariantViolated(RuntimeError):
    """Raised when an A2A tasks/resume would silently roll back local task state."""


class TaskState(IntEnum):
    SUBMITTED = 0
    WORKING = 1
    INPUT_REQUIRED = 2
    COMPLETED = 3
    CANCELED = 4
    FAILED = 5


@dataclass(frozen=True)
class Checkpoint:
    task_id: str
    state: TaskState
    history_len: int


@dataclass(frozen=True)
class RemoteCard:
    state_transition_history: bool


@dataclass(frozen=True)
class ResumeResponse:
    task_id: str
    state: TaskState
    history: Optional[list]
    push_registration_ack: bool


def guard_resume(
    checkpoint: Checkpoint,
    current_card: RemoteCard,
    resume: ResumeResponse,
) -> None:
    if checkpoint.state == TaskState.SUBMITTED:
        return  # nothing to roll back; resume is a fresh start

    history_unverifiable = (
        resume.history is None and not current_card.state_transition_history
    )
    state_rolled_back = resume.state < checkpoint.state
    push_lost = not resume.push_registration_ack

    if history_unverifiable and state_rolled_back and push_lost:
        raise ResumeInvariantViolated(
            f"refusing resume of {checkpoint.task_id}: peer dropped "
            f"stateTransitionHistory, returned state {resume.state.name} "
            f"< checkpoint {checkpoint.state.name}, and no push ack; "
            f"local state machine must freeze, not reconcile"
        )
