# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-an-a2a-v1-0-task-in-input-required-as-terminal-for-webhook-purposes-and-why-the-agent-card-s-capabilities-pus.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-an-a2a-v1-0-task-in-input-required-as-terminal-for-webhook-purposes-and-why-the-agent-card-s-capabilities-pus.warrant.json
# Markdown SHA-256:   3c5ac6956a7524b6d294894f7eb377355910116c74c90e47e8a6934ea41232bc
# Code AST SHA-256:   9389dbdd519d61d8f6e967b2a96ce9f4cbf33698d31df094bce51a626cb8d455
# Verified Classes:   A2ATaskState, PushWaitDeadlock
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from enum import Enum


class A2ATaskState(str, Enum):
    SUBMITTED = "submitted"
    WORKING = "working"
    INPUT_REQUIRED = "input-required"
    AUTH_REQUIRED = "auth-required"
    COMPLETED = "completed"
    FAILED = "failed"
    CANCELED = "canceled"


CLIENT_OWNED = {A2ATaskState.INPUT_REQUIRED, A2ATaskState.AUTH_REQUIRED}
TERMINAL = {A2ATaskState.COMPLETED, A2ATaskState.FAILED, A2ATaskState.CANCELED}


class PushWaitDeadlock(RuntimeError):
    """Raised when a caller waits on a webhook for a state the server cannot push."""


def await_next_transition(
    task_id: str,
    last_state: A2ATaskState,
    push_registered: bool,
    capabilities_push: bool,
    waited_seconds: float,
) -> str:
    # The Agent Card flag is a precondition for registration, not proof of delivery.
    if not capabilities_push:
        raise PushWaitDeadlock(
            f"task {task_id}: card declares pushNotifications=false; "
            f"webhook wait is unsound, must poll tasks/get"
        )
    if not push_registered:
        raise PushWaitDeadlock(
            f"task {task_id}: no pushNotificationConfig registered; "
            f"call tasks/pushNotificationConfig/set then reconcile with tasks/get"
        )
    # The core boundary: client-owned interrupts are never pushed.
    if last_state in CLIENT_OWNED:
        raise PushWaitDeadlock(
            f"task {task_id}: state={last_state.value} is client-owned; "
            f"server will not fire webhook. Resolve status.message and "
            f"send tasks/send with same taskId instead of waiting."
        )
    if last_state in TERMINAL:
        raise PushWaitDeadlock(
            f"task {task_id}: state={last_state.value} is terminal; "
            f"deregister webhook and stop waiting."
        )
    # last_state in {SUBMITTED, WORKING}: server owns next transition, wait is valid.
    if waited_seconds > 60.0:
        return f"task {task_id}: push silent for {waited_seconds}s in {last_state.value}; "
        # fall through to poll
    return f"task {task_id}: awaiting server-initiated transition from {last_state.value}"
