# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a2a-v1-0-capability-negotiation-as-a-two-phase-commit-rather-than-a-single-agent-card-handshake-the-phantom-c.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a2a-v1-0-capability-negotiation-as-a-two-phase-commit-rather-than-a-single-agent-card-handshake-the-phantom-c.warrant.json
# Markdown SHA-256:   66af74c867c88065f4215f749b4e1226cf5230a5a248f752ac7e283172fe3c14
# Code AST SHA-256:   79c8e05f05828248d145cdc0693dbe7568a3ec2a8f4b3c920ab6517ed34cbbcd
# Verified Classes:   CapabilityFalsifiedError, AgentCard, TaskResult, TwoPhaseRoleAssigner
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Dict, Tuple


class CapabilityFalsifiedError(RuntimeError):
    """Raised when a peer's runtime rejects a skill its AgentCard still advertises.

    This is a *negative capability observation*: the card claim is stale or the
    skill was hot-swapped/deprecated after negotiation. The (peer, skill) pair
    must be demoted from trusted to unverified and re-probed before any further
    role binding.
    """


@dataclass
class AgentCard:
    peer_id: str
    protocol_version: str
    skills: Dict[str, dict] = field(default_factory=dict)  # skill_id -> {deprecated: bool, ...}
    fetched_at: float = 0.0


@dataclass
class TaskResult:
    state: str            # "completed" | "failed"
    status_message: str   # free-form; skill-layer rejections carry "skill not found" etc.


# Skill-layer rejection markers. Transport-layer failures (timeouts, resets) are
# deliberately excluded: they are retryable against the same card.
SKILL_LAYER_MARKERS = (
    "skill not found",
    "input mode unsupported",
    "output mode unsupported",
    "schema mismatch",
)


def is_skill_layer_failure(msg: str) -> bool:
    low = msg.lower()
    return any(marker in low for marker in SKILL_LAYER_MARKERS)


class TwoPhaseRoleAssigner:
    """A2A v1.0 role assignment with dispatch-time capability probe.

    Phase 1 (advisory): match a cached AgentCard.
    Phase 2 (confirm): probe the peer's live router for the specific skill.
    Commit: only after probe success is the role binding written.
    """

    CARD_TTL_S = 3600.0

    def __init__(self, cards: Dict[str, AgentCard], probe_fn):
        self._cards = cards
        self._probe = probe_fn  # (peer_id, skill_id) -> bool, idempotent & cheap
        self._unverified: set[Tuple[str, str]] = set()  # (peer, skill) demoted pairs

    def _card_is_fresh(self, card: AgentCard) -> bool:
        return (time.time() - card.fetched_at) < self.CARD_TTL_S

    def _skill_usable(self, card: AgentCard, skill_id: str) -> bool:
        skill = card.skills.get(skill_id)
        if skill is None:
            return False
        # Deprecation is load-bearing: a deprecated skill is absent for new bindings.
        if skill.get("deprecated", False):
            return False
        return True

    def assign(self, skill_id: str, required_input_mode: str) -> str:
        candidates = [
            pid for pid, card in self._cards.items()
            if self._card_is_fresh(card)
            and self._skill_usable(card, skill_id)
            and (pid, skill_id) not in self._unverified
        ]
        if not candidates:
            raise CapabilityFalsifiedError(
                f"no verified peer advertises skill={skill_id!r} "
                f"input_mode={required_input_mode!r}; all candidates "
                f"deprecated, stale, or demoted by prior falsification"
            )

        for peer_id in candidates:
            # Phase 2: dispatch-time probe. Cheap, idempotent, semantically distinct.
            if self._probe(peer_id, skill_id):
                return peer_id  # commit the role binding
            # Probe failed: runtime does not honor the card. Demote.
            self._unverified.add((peer_id, skill_id))

        raise CapabilityFalsifiedError(
            f"all candidates falsified at probe time for skill={skill_id!r}; "
            f"card claims did not survive dispatch-time verification"
        )

    def record_dispatch_outcome(self, peer_id: str, skill_id: str, result: TaskResult) -> None:
        """Feed dispatch outcomes back into the trust model.

        A skill-layer failure is a card falsification event: it overrides the
        positive card claim and forces re-probe before the next binding.
        """
        if result.state == "failed" and is_skill_layer_failure(result.status_message):
            self._unverified.add((peer_id, skill_id))
            raise CapabilityFalsifiedError(
                f"peer={peer_id!r} rejected skill={skill_id!r} at runtime "
                f"(status={result.status_message!r}) despite advertising it in "
                f"AgentCard protocolVersion={self._cards[peer_id].protocol_version!r}; "
                f"pair demoted to unverified, re-probe required"
            )
        # Transport-layer failure or success: no trust change.
