# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reject-an-a2a-agent-card-whose-capabilities-streaming-claim-disagrees-with-the-transport-it-was-discovered-over-before-the-dele.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reject-an-a2a-agent-card-whose-capabilities-streaming-claim-disagrees-with-the-transport-it-was-discovered-over-before-the-dele.warrant.json
# Markdown SHA-256:   d17eeb40b5abba02fc1cfa7056e96a4ee2877e007f912244570273e888aad080
# Code AST SHA-256:   93e1358c58be6d1986ae0fbfe7cd33893321b33c881dc7638a9b9ba20cb596a7
# Verified Classes:   InterfaceCapabilityUnverified, AgentCard, ResolvedInterface
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from typing import Optional


class InterfaceCapabilityUnverified(RuntimeError):
    """Raised when a delegation envelope would be signed against an A2A
    interface whose capabilities were never probed and which is not the
    card's preferredTransport. Signing here risks an orphaned remote task
    and a half-open caller state on method-not-found."""


CORE_UNARY_METHODS = frozenset({"message/send", "tasks/get", "tasks/cancel"})
STREAMING_DEPENDENT = frozenset({"message/stream"})


@dataclass(frozen=True)
class AgentCard:
    preferred_transport_host: str
    capabilities_streaming: bool
    capabilities_push: bool
    additional_interface_hosts: tuple[str, ...]
    etag: Optional[str]


@dataclass(frozen=True)
class ResolvedInterface:
    host: str
    transport: str


def guard_sign(
    card: AgentCard,
    interface: ResolvedInterface,
    method: str,
    probed_capabilities: Optional[frozenset[str]],
) -> None:
    """Enforce the capability/transport join before signing a delegation
    envelope. Raises InterfaceCapabilityUnverified if the invariant fails."""
    is_preferred = interface.host == card.preferred_transport_host
    is_core_unary = method in CORE_UNARY_METHODS
    needs_streaming = method in STREAMING_DEPENDENT or (
        method.startswith("ext/") and card.capabilities_streaming
    )

    if is_preferred:
        return

    if is_core_unary:
        return

    if probed_capabilities is None:
        raise InterfaceCapabilityUnverified(
            f"refusing to sign method={method!r} against non-preferred "
            f"interface host={interface.host!r} (transport={interface.transport!r}): "
            f"no capability probe cached for (host, card.etag={card.etag!r}). "
            f"Either probe capabilities/get on this interface, degrade to "
            f"message/send with blocking=true, or route via preferredTransport."
        )

    if needs_streaming and "streaming" not in probed_capabilities:
        raise InterfaceCapabilityUnverified(
            f"interface host={interface.host!r} probed capabilities="
            f"{sorted(probed_capabilities)!r} do not include 'streaming', but "
            f"card advertises capabilities.streaming={card.capabilities_streaming}. "
            f"Card-global claim does not bind to this interface; refusing to sign "
            f"method={method!r}."
        )


def sign_envelope(card: AgentCard, interface: ResolvedInterface, method: str,
                  probed: Optional[frozenset[str]]) -> bytes:
    guard_sign(card, interface, method, probed)
    # ... canonicalize envelope, JWS-sign with org warrant ...
    return b"<signed-envelope>"
