# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-that-an-a2a-v1-0-agent-card-is-stale-relative-to-a-live-task-state-machine.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-that-an-a2a-v1-0-agent-card-is-stale-relative-to-a-live-task-state-machine.warrant.json
# Markdown SHA-256:   e584746502804a44d3b44966a75e2421bd3e77fa51b050344953eee22d034b08
# Code AST SHA-256:   0e2754744e30a039a8325f945cca21bc1f21bb4518cb07b3000b7e1639ec716e
# Verified Classes:   StaleAgentCardError, ProbeResult
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

import time
from dataclasses import dataclass
from typing import Any, Callable


class StaleAgentCardError(RuntimeError):
    """Raised when an A2A Agent Card's declared surface disagrees with the
    live task state machine or webhook emitter. The card is schema-valid but
    operationally stale; the caller should fall back to polling tasks/get."""


@dataclass(frozen=True)
class ProbeResult:
    skill_id: str
    reached_terminal: bool
    webhook_delivered: bool
    observed_states: tuple[str, ...]


def probe_capability(
    card: dict[str, Any],
    skill_id: str,
    send_task: Callable[[str], str],
    get_task: Callable[[str], dict[str, Any]],
    webhook_fired: Callable[[], bool],
    timeout_s: float = 30.0,
    poll_interval_s: float = 0.5,
) -> ProbeResult:
    """Exercise the live machine against the card's declared contract.

    The card is treated as a *hypothesis*. We send a probe task routed to
    `skill_id`, observe the state machine via tasks/get, and check whether
    the webhook emitter honored the card's pushNotifications contract.
    """
    declared_skills = {s.get("id") for s in card.get("skills", [])}
    if skill_id not in declared_skills:
        raise StaleAgentCardError(
            f"skill {skill_id!r} not present in card skills {sorted(declared_skills)}"
        )

    push_declared = bool(card.get("capabilities", {}).get("pushNotifications", False))

    task_id = send_task(skill_id)
    states: list[str] = []
    deadline = time.monotonic() + timeout_s
    reached_terminal = False

    while time.monotonic() < deadline:
        task = get_task(task_id)
        state = task.get("status", {}).get("state")
        if state and (not states or states[-1] != state):
            states.append(state)
        if state in ("completed", "failed", "canceled"):
            reached_terminal = True
            break
        time.sleep(poll_interval_s)

    webhook_delivered = webhook_fired() if push_declared else True

    # The structural staleness verdict: the card declared a skill and a
    # push contract, but the machine could not honor either.
    if not reached_terminal:
        raise StaleAgentCardError(
            f"skill {skill_id!r} never reached a terminal state "
            f"(observed states={states!r}); card is stale relative to machine"
        )
    if push_declared and not webhook_delivered:
        raise StaleAgentCardError(
            f"card declares pushNotifications=true but no webhook fired "
            f"for skill {skill_id!r} (observed states={states!r}); "
            f"fall back to polling tasks/get"
        )

    return ProbeResult(
        skill_id=skill_id,
        reached_terminal=reached_terminal,
        webhook_delivered=webhook_delivered,
        observed_states=tuple(states),
    )
