# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-advertises-a2a-v1-0-over-both-grpc-and-json-rpc-but-its-agentcard-s-preferredtransport-disagrees-with-the-binding-actual.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-advertises-a2a-v1-0-over-both-grpc-and-json-rpc-but-its-agentcard-s-preferredtransport-disagrees-with-the-binding-actual.warrant.json
# Markdown SHA-256:   76cdd6b324fe650d97a92a9eb81a5659d58a2b631ce7fb527487e30abeb781b4
# Code AST SHA-256:   79c71fc712e810cb9e4b2e3aa7f89656c3d8aa2cdd2c429e5cb085c2ee15c433
# Verified Classes:   AgentCardBindingError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class AgentCardBindingError(RuntimeError):
    """Raised when an AgentCard's declared transport set is not backed by a served binding."""
    pass


def validate_card_against_bindings(card: dict, listening: dict[str, set[str]]) -> None:
    """
    card: parsed AgentCard with 'url', 'preferredTransport', optional 'additionalInterfaces'
    listening: mapping of url -> set of transports actually served (handler registered)
    """
    primary_url = card.get("url")
    preferred = card.get("preferredTransport")
    interfaces = card.get("additionalInterfaces") or []

    declared = {(primary_url, preferred)} if preferred else set()
    declared |= {(i["url"], i["transport"]) for i in interfaces}

    for url, transport in declared:
        served = listening.get(url, set())
        if transport not in served:
            raise AgentCardBindingError(
                f"AgentCard declares transport {transport!r} at {url!r}, "
                f"but that binding is not served (served: {sorted(served) or 'none'}). "
                f"preferredTransport={preferred!r}, primary_url={primary_url!r}."
            )

    # The hint must resolve to a binding served at the primary url, or the card is misleading.
    if preferred and preferred not in listening.get(primary_url, set()):
        raise AgentCardBindingError(
            f"preferredTransport={preferred!r} is not served at primary url {primary_url!r}; "
            f"clients honoring the hint will fail before delegation."
        )


def delegate(card: dict, listening: dict[str, set[str]], send) -> object:
    validate_card_against_bindings(card, listening)
    # A client that reaches here may still treat preferredTransport as a hint and fall back,
    # but the publishing agent must never emit a card that fails this check.
    return send(card["url"], card.get("preferredTransport"))
