# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-peer-agent-card-whose-declared-taskstate-transition-graph-is-acyclic-but-omits-the-input-required-work.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-peer-agent-card-whose-declared-taskstate-transition-graph-is-acyclic-but-omits-the-input-required-work.warrant.json
# Markdown SHA-256:   2cd6cebdfe86c0231b2c33e61833a88a34af2e09d7d0480607ab858dd476b47c
# Code AST SHA-256:   9e9483e6ef242320c7afbeae63b792e89c96ab6d864c02ee669e601baabf9442
# Verified Classes:   CardResumptionInconsistency, TaskResumptionError, ResumptionMode, AgentCard, PersistedTask
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class CardResumptionInconsistency(RuntimeError):
    """Raised when a peer Agent Card's declared resumption capability
    contradicts its declared taskState transition graph."""


class TaskResumptionError(RuntimeError):
    """Raised when a persisted taskId is resumed under a mode that the
    peer's current card no longer supports."""


class ResumptionMode(str, Enum):
    SUSPEND_CAPABLE = "suspend"
    HANDOFF_ONLY = "handoff"


@dataclass(frozen=True)
class AgentCard:
    peer_id: str
    task_states: FrozenSet[str]
    transitions: FrozenSet[Tuple[str, str]]
    resumption: str | None = None  # v1.0 extension; None means spec default "handoff"


@dataclass
class PersistedTask:
    task_id: str
    context_id: str
    mode: ResumptionMode
    state: str = "submitted"
    history: list[str] = field(default_factory=list)


RESUMPTION_EDGE = ("input-required", "working")
SUSPEND_STATES = frozenset({"input-required", "paused", "awaiting-approval"})


def negotiate_resumption_mode(card: AgentCard) -> ResumptionMode:
    """Resolve the peer's resumption semantics from its card, rejecting
    internally inconsistent cards at parse time."""
    declares_suspend = card.resumption == "suspend"
    has_resumption_edges = all(
        (s, "working") in card.transitions for s in SUSPEND_STATES if s in card.task_states
    )

    if declares_suspend and not has_resumption_edges:
        raise CardResumptionInconsistency(
            f"peer {card.peer_id!r} declares resumption='suspend' but omits a "
            f"resumption edge from one of {sorted(SUSPEND_STATES & card.task_states)} "
            f"back to 'working'; transition graph is non-resumable. "
            f"Reject at negotiation, not at resume."
        )

    if declares_suspend and has_resumption_edges:
        return ResumptionMode.SUSPEND_CAPABLE

    # Absent or "handoff" resumption, OR suspend declared but edges missing
    # (unreachable given the raise above). Absence of the edge is a
    # declaration of handoff semantics, not an omission.
    return ResumptionMode.HANDOFF_ONLY


def mint_task(card: AgentCard, context_id: str, task_id: str) -> PersistedTask:
    mode = negotiate_resumption_mode(card)
    return PersistedTask(task_id=task_id, context_id=context_id, mode=mode)


def resume_task(task: PersistedTask, current_card: AgentCard, clarification: dict) -> PersistedTask:
    """Resume a suspended task. Branches on the mode tagged at mint time,
    not on the peer's current card."""
    if task.mode is ResumptionMode.HANDOFF_ONLY:
        raise TaskResumptionError(
            f"task {task.task_id!r} was minted under HANDOFF_ONLY; peer "
            f"{current_card.peer_id!r} models input-required as a terminal "
            f"handoff. Mint a new task under context {task.context_id!r} "
            f"instead of resuming {task.task_id!r}."
        )

    # Re-validate against the *current* card: a peer that downgraded between
    # turns must not receive a resume against a taskId minted under suspend.
    current_mode = negotiate_resumption_mode(current_card)
    if current_mode is not ResumptionMode.SUSPEND_CAPABLE:
        raise TaskResumptionError(
            f"peer {current_card.peer_id!r} downgraded from suspend to handoff "
            f"between turns; task {task.task_id!r} cannot be resumed. "
            f"Abandon and re-mint under context {task.context_id!r}."
        )

    if RESUMPTION_EDGE not in current_card.transitions:
        raise TaskResumptionError(
            f"peer {current_card.peer_id!r} no longer declares "
            f"{RESUMPTION_EDGE!r}; resume of {task.task_id!r} is undefined."
        )

    task.state = "working"
    task.history.append("resumed")
    return task
