# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-a2a-v1-0-agent-card-s-declared-pushnotifications-capability-as-non-binding-at-task-acceptance-time.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-a2a-v1-0-agent-card-s-declared-pushnotifications-capability-as-non-binding-at-task-acceptance-time.warrant.json
# Markdown SHA-256:   6787c246fe363c3f0ca647fa82a75d303c2f3bcee7e7166010867676d0ab0b4c
# Code AST SHA-256:   a127c4de0532b3d901949ac9eb5a901891351a5c1928514ffe83690d4f33e1b2
# Verified Classes:   PushBindingUnverified, PollFloorExceeded, Binding, TaskState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class PushBindingUnverified(RuntimeError):
    """Raised when a caller attempts to enter awaiting_notification without a
    live, reachable, token-authenticated pushNotificationConfig binding."""
    pass


class PollFloorExceeded(RuntimeError):
    """Raised when a non-terminal task has had no outstanding tasks/get for
    longer than poll_floor seconds, violating the liveness invariant."""
    pass


@dataclass
class Binding:
    id: str
    url: str
    token: str
    verified_at: Optional[float] = None
    egress_reachable: bool = False


@dataclass
class TaskState:
    task_id: str
    status: str = "submitted"          # submitted|working|completed|failed|canceled
    binding: Optional[Binding] = None
    last_poll_at: float = field(default_factory=time.time)
    poll_floor: float = 300.0


def accept_task(card_capabilities: dict, send_response: dict,
                egress_probe, now: Optional[float] = None) -> TaskState:
    """Decide whether to bind push or fall back to polling. The card's
    pushNotifications flag is deliberately NOT consulted for the binding
    decision; only the send response and the egress probe are."""
    now = now if now is not None else time.time()
    ts = TaskState(task_id=send_response["id"], status=send_response["status"])

    cfg = send_response.get("pushNotificationConfig")
    if not cfg or not cfg.get("id") or not cfg.get("token"):
        # Card may say true; response says no binding. Poll.
        ts.binding = None
        ts.last_poll_at = now
        return ts

    binding = Binding(id=cfg["id"], url=cfg["url"], token=cfg["token"])
    binding.egress_reachable = bool(egress_probe(cfg["url"]))
    binding.verified_at = now if binding.egress_reachable else None

    if not binding.egress_reachable:
        # Peer accepted the registration but cannot reach us. Treat as
        # unbound; polling is the only liveness path.
        ts.binding = None
        ts.last_poll_at = now
        return ts

    ts.binding = binding
    ts.last_poll_at = now
    return ts


def enter_awaiting_notification(ts: TaskState, now: Optional[float] = None) -> None:
    now = now if now is not None else time.time()
    if ts.binding is None or not ts.binding.egress_reachable or not ts.binding.token:
        raise PushBindingUnverified(
            f"task {ts.task_id}: cannot enter awaiting_notification without a "
            f"verified binding (id={getattr(ts.binding,'id',None)}, "
            f"reachable={getattr(ts.binding,'egress_reachable',False)}); "
            f"card capability is not sufficient evidence"
        )
    ts.status = "awaiting_notification"


def check_poll_floor(ts: TaskState, now: Optional[float] = None) -> None:
    now = now if now is not None else time.time()
    if ts.status in ("completed", "failed", "canceled"):
        return
    if now - ts.last_poll_at > ts.poll_floor:
        raise PollFloorExceeded(
            f"task {ts.task_id}: {now - ts.last_poll_at:.0f}s since last "
            f"tasks/get exceeds poll_floor={ts.poll_floor}s; push binding "
            f"{getattr(ts.binding,'id',None)} did not deliver and no fallback "
            f"poll was issued"
        )


def validate_webhook(ts: TaskState, authorization_header: str) -> None:
    if ts.binding is None:
        raise PushBindingUnverified(f"task {ts.task_id}: webhook arrived with no binding")
    presented = authorization_header.removeprefix("Bearer ").strip()
    if presented != ts.binding.token:
        # Server rotated token on re-registration; caller must re-probe.
        raise PushBindingUnverified(
            f"task {ts.task_id}: webhook token mismatch for binding "
            f"{ts.binding.id}; re-verify pushNotificationConfig before "
            f"accepting delivery"
        )
