# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-an-a2a-v1-0-agent-card-that-advertises-a-task-state-transition-the-receiving-lifecycle-machine-cannot-honor.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-an-a2a-v1-0-agent-card-that-advertises-a-task-state-transition-the-receiving-lifecycle-machine-cannot-honor.warrant.json
# Markdown SHA-256:   cf03d87cd3aeedf0ed92ef14d09eb9af0c50f72d922cbd9f5268ef724bde0668
# Code AST SHA-256:   0059cdabea8ce2fb2686a7d89071da6a0a64ac4a380c2ac4cff2d9e03aea4ff1
# Verified Classes:   CardConformanceError, ReceiverMachine, AgentCard
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Set, Tuple


class CardConformanceError(RuntimeError):
    """Raised when an A2A agent card is not conformant for this receiver."""
    pass


@dataclass
class ReceiverMachine:
    states: Set[str]
    edges: Set[Tuple[str, str]]
    has_reply_channel: bool
    has_idempotency: bool

    def can_enter(self, state: str) -> bool:
        return state in self.states

    def has_edge(self, src: str, dst: str) -> bool:
        return (src, dst) in self.edges


@dataclass
class AgentCard:
    advertised_states: Set[str]
    streaming: bool = False
    push_notifications: bool = False
    closed_world: bool = False
    # If closed_world is False, omission is NOT prohibition.
    implied_states: Set[str] = field(default_factory=lambda: {"failed", "canceled"})


def validate_card_for_receiver(card: AgentCard, recv: ReceiverMachine) -> None:
    # Effective emit-set: advertised is a lower bound unless closed_world.
    emit_set = set(card.advertised_states)
    if not card.closed_world:
        emit_set |= card.implied_states

    # 1. Emit-reachability: every emittable state must be enterable.
    unmapped = {s for s in emit_set if not recv.can_enter(s)}
    if unmapped:
        raise CardConformanceError(
            f"peer can emit states receiver cannot enter: {sorted(unmapped)}"
        )

    # 2. Transition-legality: input-required needs a resume edge + reply channel.
    if "input-required" in emit_set:
        if not recv.has_edge("working", "input-required"):
            raise CardConformanceError(
                "peer emits 'input-required' but receiver has no "
                "(working -> input-required) edge"
            )
        if not recv.has_edge("input-required", "working"):
            raise CardConformanceError(
                "peer emits 'input-required' but receiver has no resume edge "
                "(input-required -> working)"
            )
        if not recv.has_reply_channel:
            raise CardConformanceError(
                "peer emits 'input-required' but receiver has no reply transport"
            )

    # 3. Streaming without partial-update handling masks stalls.
    if card.streaming and not recv.has_edge("working", "working"):
        raise CardConformanceError(
            "peer advertises streaming but receiver has no partial-update "
            "self-loop on 'working'"
        )

    # 4. Push notifications require idempotency on inbound replay.
    if card.push_notifications and not recv.has_idempotency:
        raise CardConformanceError(
            "peer advertises pushNotifications but receiver lacks idempotency "
            "keys; replayed 'completed' will double-apply"
        )


def negotiate(card: AgentCard, recv: ReceiverMachine) -> bool:
    validate_card_for_receiver(card, recv)
    return True
