# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a2a-v1-0-agent-card-skills-inputmodes-as-a-negotiated-commitment-rather-than-a-discovery-hint-and-what-breaks.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a2a-v1-0-agent-card-skills-inputmodes-as-a-negotiated-commitment-rather-than-a-discovery-hint-and-what-breaks.warrant.json
# Markdown SHA-256:   1e8daf68d2ee83b7bb80ba55df299e4f899199ce09b8d03deeea050faecdcd8f
# Code AST SHA-256:   39c7f668e67868141f25889484c8e5f7a74cc4a35929077affc1ad836ec1d8ea
# Verified Classes:   ModeNegotiationError, TaskState, Skill, AgentCard
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class ModeNegotiationError(RuntimeError):
    """Raised when a dispatch or resume violates the effective-input-mode invariant."""


class TaskState(str, Enum):
    SUBMITTED = "submitted"
    WORKING = "working"
    COMPLETED = "completed"
    FAILED = "failed"
    CANCELED = "canceled"
    REJECTED = "rejected"


# The partition that the caller MUST enforce. rejected is NOT success-adjacent.
SUCCESS_TERMINAL = {TaskState.COMPLETED}
FAILURE_TERMINAL = {TaskState.FAILED, TaskState.CANCELED, TaskState.REJECTED}


@dataclass
class Skill:
    id: str
    input_modes: Optional[list[str]] = None  # None => inherit defaults


@dataclass
class AgentCard:
    default_input_modes: list[str]
    skills: dict[str, Skill] = field(default_factory=dict)


def effective_input_modes(card: AgentCard, skill_id: str) -> set[str]:
    skill = card.skills.get(skill_id)
    if skill is None:
        raise ModeNegotiationError(f"skill {skill_id!r} not present in card")
    # Override semantics: per-skill array REPLACES defaults, never extends.
    modes = skill.input_modes if skill.input_modes is not None else card.default_input_modes
    return set(modes)


def resolve_dispatch_mode(card: AgentCard, skill_id: str, part_kind: str) -> str:
    accepted = effective_input_modes(card, skill_id)
    if part_kind not in accepted:
        raise ModeNegotiationError(
            f"part kind {part_kind!r} not accepted by skill {skill_id!r}; "
            f"effective modes={sorted(accepted)}"
        )
    return part_kind


def classify_closure(state: TaskState, status_message: Optional[str]) -> str:
    if state in SUCCESS_TERMINAL:
        return "proceed"
    if state in FAILURE_TERMINAL:
        # rejected carries negotiation diagnostics; surface, do not swallow.
        raise ModeNegotiationError(
            f"task closed in {state.value!r}: {status_message or 'no status message'}"
        )
    raise ModeNegotiationError(f"non-terminal state {state.value!r} passed to closure gate")


# Reproduction of the observed trace.
card = AgentCard(
    default_input_modes=["text/plain", "application/json"],
    skills={
        "extract_pdf": Skill(id="extract_pdf", input_modes=["application/pdf"]),
        "extract_text": Skill(id="extract_text", input_modes=["text/plain"]),
    },
)

# Caller mistakenly serializes a PDF as a text part (default-mode-driven serializer).
try:
    resolve_dispatch_mode(card, "extract_pdf", part_kind="text")
except ModeNegotiationError as e:
    print("dispatch blocked:", e)

# Even if the remote had accepted and later rejected, closure gate must halt.
try:
    classify_closure(TaskState.REJECTED, "unsupported input mode for skill")
except ModeNegotiationError as e:
    print("closure halted:", e)
