# 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-capabilities-streaming-as-a-per-task-negotiation-outcome-rather-than-a-static-discovery-f.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a2a-v1-0-agent-card-capabilities-streaming-as-a-per-task-negotiation-outcome-rather-than-a-static-discovery-f.warrant.json
# Markdown SHA-256:   e26bd06b3aa0121414bf8a3dfc6168bcf167804e2f72ec3b4864e8b29f26a56f
# Code AST SHA-256:   168ead098126dcd318cf0e3de014944b405abf891284d6e9861c3a7360668b96
# Verified Classes:   CapabilityNegotiationError, SkillCard, AgentCard
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class CapabilityNegotiationError(RuntimeError):
    """Raised when a card-level streaming claim cannot be exercised by the
    selected skill, or when a stream opens but terminates before any
    non-terminal event. Distinct from TaskExecutionError — the task never
    really started."""


@dataclass
class SkillCard:
    skill_id: str
    output_modes: Optional[list[str]]  # None => inherit agent defaults


@dataclass
class AgentCard:
    capabilities_streaming: bool
    default_output_modes: list[str]
    skills: list[SkillCard]

    def resolve_skill(self, skill_id: str) -> SkillCard:
        for s in self.skills:
            if s.skill_id == skill_id:
                return s
        raise CapabilityNegotiationError(f"skill {skill_id!r} not advertised on card")


STREAM_COMPATIBLE = {"text/event-stream"}


def choose_transport(card: AgentCard, skill_id: str, payload_modality: str) -> str:
    """Return 'sendSubscribe' or 'send'. Raises if the card lies about a skill."""
    skill = card.resolve_skill(skill_id)
    modes = skill.output_modes if skill.output_modes is not None else card.default_output_modes

    stream_ok = card.capabilities_streaming and bool(STREAM_COMPATIBLE & set(modes))

    if card.capabilities_streaming and not stream_ok:
        # Card says streaming; skill says no. This is the exact trap.
        raise CapabilityNegotiationError(
            f"agent advertises capabilities.streaming=true but skill {skill_id!r} "
            f"outputModes={modes} expose no event-stream mode; "
            f"refusing sendSubscribe, must use tasks/send"
        )

    if payload_modality not in modes and payload_modality != "text/plain":
        raise CapabilityNegotiationError(
            f"payload modality {payload_modality!r} not in skill {skill_id!r} "
            f"outputModes={modes}"
        )

    return "sendSubscribe" if stream_ok else "send"


def validate_first_event(first_event_state: str, event_kind: str) -> None:
    """Post-open guard: a terminal 'failed' as the very first event means the
    remote accepted the HTTP stream but could not honor the task — negotiate,
    do not execute."""
    if event_kind == "TaskStatusUpdateEvent" and first_event_state == "failed":
        raise CapabilityNegotiationError(
            "stream opened but terminated on first event with state=failed; "
            "discard taskId and renegotiate via tasks/send with a fresh id"
        )
