# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-acknowledge-an-a2a-task-it-has-already-accepted-the-accepted-but-unbound-window-in-agent-card-discovery-and-push-notif.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-acknowledge-an-a2a-task-it-has-already-accepted-the-accepted-but-unbound-window-in-agent-card-discovery-and-push-notif.warrant.json
# Markdown SHA-256:   54848fd729323302b7a0f15776187336aa6d0d3c18e65173cd576b28040d9b41
# Code AST SHA-256:   a7e1f0c75a5705d3401b1a5e677c6f2d6898bcf39cf0a5f109a4381ff3d32ea0
# Verified Classes:   PushBindingError, BindingState, PushConfig, Task
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class PushBindingError(RuntimeError):
    """Raised when a task cannot be acknowledged because its push-notification
    webhook could not be bound and the agent's contract forbids returning a
    'working' task on an unobservable channel."""


class BindingState(str, Enum):
    VERIFIED = "verified"
    PENDING = "pending"
    UNVERIFIED = "unverified"


@dataclass
class PushConfig:
    url: str
    state: BindingState = BindingState.PENDING
    attempts: int = 0


@dataclass
class Task:
    id: str
    state: str = "submitted"
    push_config: Optional[PushConfig] = None
    notes: list = field(default_factory=list)


DEFINITIVE_FAILURES = {"connection_refused", "tls_error", "http_403", "http_404"}


def _probe(url: str) -> str:
    # Stub: in production this performs a HEAD/OPTIONS with a signed nonce.
    # Returns a symbolic outcome string.
    return "ok"


def bind_push_config(cfg: PushConfig, budget_seconds: float = 6.0) -> BindingState:
    backoff = [0.25, 1.0, 4.0]
    deadline = time.monotonic() + budget_seconds
    for delay in backoff:
        if time.monotonic() + delay > deadline:
            break
        time.sleep(delay)
        cfg.attempts += 1
        outcome = _probe(cfg.url)
        if outcome == "ok":
            cfg.state = BindingState.VERIFIED
            return cfg.state
        if outcome in DEFINITIVE_FAILURES:
            cfg.state = BindingState.UNVERIFIED
            return cfg.state
        # timeout / 5xx / 429 -> keep retrying within budget
    cfg.state = BindingState.PENDING
    return cfg.state


def handle_message_send(task: Task, push_supported: bool) -> Task:
    if task.push_config is None:
        task.state = "working"
        return task

    if not push_supported:
        raise PushBindingError(
            f"task {task.id}: client supplied pushNotificationConfig but this "
            f"agent's Agent Card declares capabilities.pushNotifications=false"
        )

    state = bind_push_config(task.push_config)

    if state is BindingState.VERIFIED:
        task.state = "working"
        return task

    if state is BindingState.UNVERIFIED:
        # Definitive failure: refuse to hand back a 'working' task on a
        # channel the client cannot observe. Surface as submitted + message.
        task.state = "submitted"
        task.notes.append(
            f"push binding to {task.push_config.url} failed definitively after "
            f"{task.push_config.attempts} attempt(s); re-supply a config or poll"
        )
        raise PushBindingError(
            f"task {task.id}: push binding failed definitively; refusing to "
            f"acknowledge as 'working'"
        )

    # PENDING: non-definitive failure within budget exhausted. Accept but
    # mark input-required so the client knows to act.
    task.state = "input-required"
    task.notes.append(
        f"push binding to {task.push_config.url} still pending after "
        f"{task.push_config.attempts} attempt(s); background retry capped at 5m"
    )
    return task
