# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reject-a-peer-s-agent-card-when-the-signature-validates-but-the-task-state-machine-is-incompatible.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reject-a-peer-s-agent-card-when-the-signature-validates-but-the-task-state-machine-is-incompatible.warrant.json
# Markdown SHA-256:   58d48a599c509f8bc26495f5206287676ab4cd36469290b8ff29b5b80bbe65d8
# Code AST SHA-256:   5bebb1e2808d71076a1f0eb4a54e8be7f7d496a8f66d4a279fc7b45b48f6427c
# Verified Classes:   CardAdmissibilityError, CallerState, PeerLifecycle, AgentCard, CallerProfile
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import Iterable


class CardAdmissibilityError(RuntimeError):
    """Raised when a cryptographically valid Agent Card is operationally inadmissible."""


class CallerState(str, Enum):
    SUBMITTED = "submitted"
    WORKING = "working"
    AWAITING_INPUT = "awaiting_input"
    COMPLETED = "completed"
    CANCELED = "canceled"


# Caller states that imply the caller must act; coercing a peer state into
# one of these is only safe if the peer state genuinely requires no action.
PASSIVE_CALLER_STATES = {CallerState.WORKING, CallerState.SUBMITTED}


@dataclass(frozen=True)
class PeerLifecycle:
    states: frozenset[str]
    action_requiring: frozenset[str]      # peer states that demand a caller follow-up
    terminal_states: frozenset[str]
    signed_terminal_states: frozenset[str]  # terminal states that MUST carry a signed artifact
    task_ttl_seconds: int


@dataclass(frozen=True)
class AgentCard:
    signature_valid: bool
    lifecycle: PeerLifecycle
    artifact_key_refs: frozenset[str]


@dataclass
class CallerProfile:
    coercion_table: dict[str, CallerState] = field(default_factory=dict)
    pinned_key_refs: set[str] = field(default_factory=set)
    task_deadline_seconds: int = 240
    poll_interval_seconds: int = 2


def assert_admissible(card: AgentCard, caller: CallerProfile) -> None:
    """Pre-delegation gate. Must pass before the first task message is emitted."""
    if not card.signature_valid:
        raise CardAdmissibilityError("card signature invalid; reject at crypto layer")

    lc = card.lifecycle

    # 1. Every peer-emittable state must have a handler or coercion.
    unmapped = lc.states - set(caller.coercion_table)
    if unmapped:
        raise CardAdmissibilityError(
            f"peer states without caller handler or coercion: {sorted(unmapped)}"
        )

    # 2. No action-requiring peer state may coerce to a passive caller state.
    for peer_state in lc.action_requiring:
        mapped = caller.coercion_table.get(peer_state)
        if mapped in PASSIVE_CALLER_STATES:
            raise CardAdmissibilityError(
                f"peer state {peer_state!r} requires caller action but coerces to "
                f"passive caller state {mapped.value!r}; this stalls the task silently"
            )

    # 3. Terminal artifact contract must be explicit and consistent.
    if not lc.terminal_states:
        raise CardAdmissibilityError("peer declares no terminal states")
    if not lc.signed_terminal_states <= lc.terminal_states:
        raise CardAdmissibilityError(
            "signed_terminal_states is not a subset of terminal_states; contract ambiguous"
        )

    # 4. All artifact keys must be pre-pinned before submission.
    unpinned = card.artifact_key_refs - caller.pinned_key_refs
    if unpinned:
        raise CardAdmissibilityError(
            f"artifact keys not pinned at discovery time: {sorted(unpinned)}"
        )

    # 5. TTL must fit inside the caller's own deadline with one poll margin.
    if lc.task_ttl_seconds > caller.task_deadline_seconds - caller.poll_interval_seconds:
        raise CardAdmissibilityError(
            f"peer TTL {lc.task_ttl_seconds}s exceeds caller deadline "
            f"{caller.task_deadline_seconds}s minus one poll interval"
        )


def admit_peer(card: AgentCard, caller: CallerProfile) -> bool:
    assert_admissible(card, caller)
    return True
