# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-an-a2a-v1-0-agent-card-whose-declared-capabilities-streaming-contradicts-the-transport-it-was-discovered-over.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-an-a2a-v1-0-agent-card-whose-declared-capabilities-streaming-contradicts-the-transport-it-was-discovered-over.warrant.json
# Markdown SHA-256:   6f80b044e99fbced84805d0de9189efa9c534a130e0ccaa6ff51e9179fcb90d4
# Code AST SHA-256:   9ac39c64ca5c07606dec45322f6c9f50816e2f4593fe1864595addb12939b2ba
# Verified Classes:   A2ATransportMismatch, AgentInterface, AgentCard
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class A2ATransportMismatch(RuntimeError):
    """Raised when an Agent Card's declared capabilities contradict the
    transport bindings it actually exposes, or when a streaming negotiation
    fails to produce a first event within the deadline."""
    pass


@dataclass
class AgentInterface:
    transport: str
    url: str


@dataclass
class AgentCard:
    name: str
    capabilities_streaming: bool
    preferred_transport: str
    additional_interfaces: list = field(default_factory=list)


STREAMING_TRANSPORTS = {"SSE", "WEBSOCKET", "GRPC_STREAM"}


def select_transport(card: AgentCard, target_url: str) -> str:
    """Choose a transport for a task against `target_url`.

    Normative source is `additional_interfaces`, NOT the capability boolean.
    Returns 'stream' or 'sync'. Raises on unbound or contradictory cards.
    """
    matching = [i for i in card.additional_interfaces if i.url == target_url]
    streaming_ifaces = [i for i in matching if i.transport in STREAMING_TRANSPORTS]

    if card.capabilities_streaming and not streaming_ifaces:
        # Boolean over-promises: claimed streaming with no bound interface.
        raise A2ATransportMismatch(
            f"card {card.name!r} declares capabilities.streaming=true but no "
            f"streaming interface is bound to {target_url!r}; refusing to stream"
        )

    if card.capabilities_streaming and streaming_ifaces:
        return "stream"

    if not card.capabilities_streaming and streaming_ifaces:
        # Interface list wins; streaming available but not primary.
        return "sync"

    return "sync"


def negotiate_streaming(card: AgentCard, target_url: str,
                        first_event_deadline_s: float = 8.0,
                        open_stream_fn=None) -> str:
    """Open a stream and require a first event before the deadline.

    On deadline miss, raise and force caller into tasks/get reconciliation.
    """
    transport = select_transport(card, target_url)
    if transport != "stream":
        return "sync"

    stream = open_stream_fn(target_url)  # returns iterator of events
    start = time.monotonic()
    for event in stream:
        if time.monotonic() - start > first_event_deadline_s:
            raise A2ATransportMismatch(
                f"no first event from {target_url!r} within "
                f"{first_event_deadline_s}s; task may be executing server-side, "
                f"issue tasks/get before marking failed"
            )
        return "streaming-active"

    raise A2ATransportMismatch(
        f"stream to {target_url!r} closed with zero events; "
        f"do not degrade to sync silently"
    )
