# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reject-a-delegated-a2a-task-when-the-remote-agent-card-s-securityschemes-are-structurally-valid-but-semantically-unsatisfiable.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reject-a-delegated-a2a-task-when-the-remote-agent-card-s-securityschemes-are-structurally-valid-but-semantically-unsatisfiable.warrant.json
# Markdown SHA-256:   97f92a67618e9c7b10f5019da3baa32fb8a3759f79d8bee838254aff34b8355f
# Code AST SHA-256:   c54c6184d4f1837bb5dd957fe2a0a131052dcc9df80a609221276d83cc9ae856
# Verified Classes:   UnsatisfiableAgentCardError, CallerCredential, SecurityRequirement
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class UnsatisfiableAgentCardError(RuntimeError):
    """Raised when a structurally valid A2A Agent Card's security requirement
    cannot be satisfied by the caller's credential across its full operation set.
    This is a pre-dispatch, fail-closed condition: no remote task is created."""


@dataclass
class CallerCredential:
    token_type: str          # e.g. "oauth2", "mtls"
    issuer_host: str         # host of the IdP that minted this credential
    scopes: frozenset[str]
    federated_issuers: frozenset[str] = field(default_factory=frozenset)


@dataclass
class SecurityRequirement:
    # A2A: one requirement object is CONJUNCTIVE across its named schemes.
    schemes: dict[str, list[str]]   # scheme_name -> required scopes
    token_url_hosts: dict[str, str] # scheme_name -> issuer host from tokenUrl


def assert_requirement_satisfiable(
    requirement: SecurityRequirement,
    credential: CallerCredential,
    operations: Iterable[str],          # e.g. {"tasks/send", "tasks/get", "tasks/cancel"}
    per_operation_scopes: dict[str, set[str]],
) -> None:
    """Fail closed unless the single credential satisfies EVERY scheme named in
    the requirement AND covers the scope union of all operations the caller
    intends to invoke. Raises UnsatisfiableAgentCardError otherwise."""
    for scheme_name, required_scopes in requirement.schemes.items():
        if scheme_name != credential.token_type:
            raise UnsatisfiableAgentCardError(
                f"requirement names scheme {scheme_name!r} but caller holds "
                f"{credential.token_type!r}; requirement entries are conjunctive"
            )
        issuer = requirement.token_url_hosts.get(scheme_name, "")
        if issuer and issuer != credential.issuer_host and issuer not in credential.federated_issuers:
            raise UnsatisfiableAgentCardError(
                f"scheme {scheme_name!r} issues from {issuer!r}; caller token is from "
                f"{credential.issuer_host!r} with no configured federation trust"
            )
        missing = frozenset(required_scopes) - credential.scopes
        if missing:
            raise UnsatisfiableAgentCardError(
                f"scheme {scheme_name!r} requires scopes {sorted(missing)} "
                f"not present on caller credential"
            )

    # The non-obvious clause: the requirement is satisfied per-operation, but the
    # card does not expose per-operation enforcement. Require coverage of the union.
    needed: set[str] = set()
    for op in operations:
        needed |= per_operation_scopes.get(op, set())
    uncovered = frozenset(needed) - credential.scopes
    if uncovered:
        raise UnsatisfiableAgentCardError(
            f"caller operations {sorted(operations)} require scope union "
            f"{sorted(needed)}; credential lacks {sorted(uncovered)} — "
            f"poll/read path would be denied after submit mutates remote state"
        )
