# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-peer-s-terminal-task-status-update-when-the-a2a-v1-0-agent-card-advertises-a-push-notification-webhook.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-peer-s-terminal-task-status-update-when-the-a2a-v1-0-agent-card-advertises-a-push-notification-webhook.warrant.json
# Markdown SHA-256:   6d5def1b33a2ef7b18d5142748a264e290995fbbbc9d8d9d77bed22cf504c6c0
# Code AST SHA-256:   37aee79ffecae9cf882bdcfda7430d2c7b0be336379bed4ad7e44acf8967499f
# Verified Classes:   UnboundTerminalStatusError, Binding, TaskState
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class UnboundTerminalStatusError(RuntimeError):
    """Raised when a terminal task status arrives before webhook binding is durable."""
    pass


@dataclass
class Binding:
    task_id: str
    bound_at: float


@dataclass
class TaskState:
    task_id: str
    state: str = "submitted"
    polling_fallback: bool = False
    binding: Optional[Binding] = None
    applied_terminal: bool = False


def accept_status_frame(
    task: TaskState,
    incoming_state: str,
    peer_push_enabled: bool,
    transport_ordered: bool,
    transition_at: float,
) -> str:
    terminal = incoming_state in ("completed", "failed", "canceled")

    if not terminal:
        task.state = incoming_state
        return task.state

    # Non-terminal path already handled. Now the boundary condition.
    if not peer_push_enabled or transport_ordered or task.polling_fallback:
        task.state = incoming_state
        task.applied_terminal = True
        return task.state

    if task.binding is None:
        # Hold, do not accept, do not silently drop.
        task.state = "TERMINAL_PENDING_BIND"
        raise UnboundTerminalStatusError(
            f"task {task.task_id}: terminal '{incoming_state}' at {transition_at} "
            f"but no durable webhook binding; held in TERMINAL_PENDING_BIND"
        )

    if task.binding.bound_at > transition_at:
        task.state = "TERMINAL_PENDING_BIND"
        raise UnboundTerminalStatusError(
            f"task {task.task_id}: binding at {task.binding.bound_at} postdates "
            f"terminal transition at {transition_at}; refusing acceptance"
        )

    if task.applied_terminal:
        # Idempotent re-application via composite key; no self-transition abort.
        return task.state

    task.state = incoming_state
    task.applied_terminal = True
    return task.state
