# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resolves-an-a2a-agent-card-whose-declared-skills-and-declared-task-lifecycle-capabilities-disagree-at-the-moment-of-task.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resolves-an-a2a-agent-card-whose-declared-skills-and-declared-task-lifecycle-capabilities-disagree-at-the-moment-of-task.warrant.json
# Markdown SHA-256:   dc0685150eae6c572d7462504831d9d8b6f388b95d4419759f90a5430361b939
# Code AST SHA-256:   17f52f18670d2c9282561296488dc63a20c8709fe4b3b271f113866b1ab4e74b
# Verified Classes:   TerminalStateDivergence, PollLivenessExceeded, AgentCard, TaskView
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

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

# The protocol's closed terminal-state set for A2A v1.0.
PROTOCOL_TERMINAL: frozenset[str] = frozenset(
    {"completed", "failed", "canceled", "rejected"}
)


class TerminalStateDivergence(RuntimeError):
    """Raised when a task reaches a protocol terminal state not declared in the card."""


class PollLivenessExceeded(RuntimeError):
    """Raised when a poll loop exceeds its wall-clock bound without reaching terminal."""


@dataclass
class AgentCard:
    name: str
    declared_terminal: frozenset[str]
    streaming: bool = False
    state_transition_history: bool = False


@dataclass
class TaskView:
    task_id: str
    state: str
    message: str | None = None


def poll_until_terminal(
    card: AgentCard,
    task_id: str,
    fetch: Callable[[str], TaskView],
    *,
    wall_clock_bound_s: float,
    poll_interval_s: float = 0.5,
) -> TaskView:
    """
    Poll a task to terminality using the PROTOCOL recognition set, not the card's
    declared set. Raise TerminalStateDivergence if the observed terminal state was
    not declared in the card (the card is under-declared; surface it, do not hang).
    """
    if not card.state_transition_history and wall_clock_bound_s <= 0:
        # History is off: polling is mandatory and must be bounded.
        raise PollLivenessExceeded(
            f"card {card.name!r} disables stateTransitionHistory; "
            "poll loop requires a positive wall-clock bound"
        )

    deadline = time.monotonic() + wall_clock_bound_s
    while True:
        view = fetch(task_id)

        if view.state in PROTOCOL_TERMINAL:
            if view.state not in card.declared_terminal:
                raise TerminalStateDivergence(
                    f"task {task_id!r} reached terminal state {view.state!r} "
                    f"which card {card.name!r} did not declare "
                    f"(declared={sorted(card.declared_terminal)}); "
                    f"remote={view.message!r}"
                )
            return view

        if time.monotonic() >= deadline:
            raise PollLivenessExceeded(
                f"task {task_id!r} still in state {view.state!r} after "
                f"{wall_clock_bound_s}s; last message={view.message!r}"
            )

        time.sleep(poll_interval_s)


def submit_and_await(
    card: AgentCard,
    submit: Callable[[str], TaskView],
    fetch: Callable[[str], TaskView],
    payload: dict,
    *,
    wall_clock_bound_s: float = 300.0,
) -> TaskView:
    accepted = submit(payload)
    if accepted.state in PROTOCOL_TERMINAL:
        # Fast-path: admission rejection (e.g. 'rejected' at submit time).
        if accepted.state not in card.declared_terminal:
            raise TerminalStateDivergence(
                f"task {accepted.task_id!r} was {accepted.state!r} at admission "
                f"but card {card.name!r} declared {sorted(card.declared_terminal)}"
            )
        return accepted
    return poll_until_terminal(
        card, accepted.task_id, fetch, wall_clock_bound_s=wall_clock_bound_s
    )
