# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a2a-agent-card-capabilities-streaming-as-a-lie-and-refuse-task-acceptance-at-the-submitted-working-transition.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a2a-agent-card-capabilities-streaming-as-a-lie-and-refuse-task-acceptance-at-the-submitted-working-transition.warrant.json
# Markdown SHA-256:   e70145bd5540f1a83facefe205f2880a697b481121c1b4f18f2c7613cb262c6b
# Code AST SHA-256:   2fccf0000659e25b84f2ba03b779f5a0e4b856c940049bc16630cc12d3cf30df
# Verified Classes:   A2ACardCapabilityViolation, TaskHandle
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class A2ACardCapabilityViolation(RuntimeError):
    """Raised when a client attempts an action that trusts a declared Agent Card capability
    past the point where the task lifecycle state machine can still corroborate it."""


@dataclass
class TaskHandle:
    task_id: str
    state: str  # submitted | working | input-required | completed | failed | canceled
    dispatched_at: float
    card_declared_streaming: bool


def guarded_resend(
    handle: TaskHandle,
    *,
    stream_open_failed: bool,
    transition_watchdog_s: float = 120.0,
    now: Optional[float] = None,
) -> str:
    """Decide whether a message/send re-issue is legal for an existing task handle.

    Returns the action to take: 'probe' (tasks/get), 'resend' (legal), or 'wait'.
    Raises A2ACardCapabilityViolation when the caller is about to trust a card
    capability across the submitted->working edge without corroboration.
    """
    now = time.monotonic() if now is None else now
    elapsed = now - handle.dispatched_at

    # Invariant: a task in 'submitted' is not committed to a transport.
    # Stream silence is not transport failure; only a tasks/get probe can tell us.
    if handle.state == "submitted":
        if stream_open_failed and elapsed < 5.0:
            # Connection itself never established; retry the *connection*, not the send.
            return "probe"
        if elapsed >= transition_watchdog_s:
            # Congested remote, not broken. Probe before any escalation.
            return "probe"
        if handle.card_declared_streaming and stream_open_failed:
            raise A2ACardCapabilityViolation(
                f"task {handle.task_id}: card declared streaming=true but stream never opened; "
                f"refusing to re-send while state=submitted — issue tasks/get first"
            )
        return "wait"

    if handle.state in ("failed", "canceled"):
        # Terminal failure: re-send is legal and must carry a fresh messageId.
        return "resend"

    if handle.state in ("working", "input-required", "completed"):
        # Re-send here would create a duplicate task; the id is the correlation handle.
        raise A2ACardCapabilityViolation(
            f"task {handle.task_id}: re-send attempted in state={handle.state}; "
            f"this would duplicate execution and artifact signing"
        )

    raise A2ACardCapabilityViolation(f"task {handle.task_id}: unknown state {handle.state!r}")


def accept_artifact(task_id: str, committed_task_ids: set[str]) -> None:
    """Reject artifacts whose taskId was not committed at dispatch time."""
    if task_id not in committed_task_ids:
        raise A2ACardCapabilityViolation(
            f"artifact for uncommitted task {task_id}; possible duplicate-task divergence"
        )
