# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-signed-a2a-v1-0-agent-card-whose-capabilities-streaming-is-true-but-whose-delegation-envelope-lacks-a-runt.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-signed-a2a-v1-0-agent-card-whose-capabilities-streaming-is-true-but-whose-delegation-envelope-lacks-a-runt.warrant.json
# Markdown SHA-256:   99f242df8be0bfecf0ea65ec026713bd90c19055c9b1f25c55497982d8cefefe
# Code AST SHA-256:   87fa957fa8f10457a068845c90f3b9f12d17d4924d38210677bb28c537ecf0e0
# Verified Classes:   RuntimeBindingError, AgentCard, DelegationEnvelope
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class RuntimeBindingError(RuntimeError):
    """Raised when a signed A2A delegation envelope cannot be bound to the
    runtime instance that advertised the capability the initiator depends on."""


@dataclass
class AgentCard:
    agent_id: str
    streaming: bool
    security_schemes: list[str]


@dataclass
class DelegationEnvelope:
    iss: str
    aud: str
    runtime_binding: Optional[str]  # vendor:version:digest, or None
    signature_valid: bool


def aud_resolves_to_single_instance(aud: str, registry: dict[str, int]) -> bool:
    return registry.get(aud, 0) == 1


def validate_delegation(
    card: AgentCard,
    envelope: DelegationEnvelope,
    initiator_depends_on_streaming: bool,
    registry: dict[str, int],
    out_of_band_attestation: Optional[str] = None,
) -> str:
    if not envelope.signature_valid:
        raise RuntimeBindingError(f"envelope from {envelope.iss} failed signature check")

    if envelope.aud != card.agent_id:
        raise RuntimeBindingError(
            f"envelope aud={envelope.aud!r} does not match card agent_id={card.agent_id!r}"
        )

    capability_dependency = initiator_depends_on_streaming and card.streaming
    if not capability_dependency:
        # Opportunistic caller: accept, but caller must downgrade to unary.
        return "accepted-degraded"

    single_instance = aud_resolves_to_single_instance(envelope.aud, registry)
    has_binding = envelope.runtime_binding is not None or out_of_band_attestation is not None

    if single_instance:
        return "accepted-implicit-binding"

    if not has_binding:
        raise RuntimeBindingError(
            "streaming-dependent delegation to multi-instance aud="
            f"{envelope.aud!r} lacks runtime_binding and out-of-band attestation; "
            "card capability cannot be bound to a concrete executor"
        )

    binding = envelope.runtime_binding or out_of_band_attestation
    digest = hashlib.sha256(binding.encode()).hexdigest()
    return f"accepted-bound:{digest[:12]}"
