# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a2a-v1-0-agent-card-capabilities-pushnotifications-as-a-per-task-negotiated-warrant-rather-than-a-vendor-leve.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a2a-v1-0-agent-card-capabilities-pushnotifications-as-a-per-task-negotiated-warrant-rather-than-a-vendor-leve.warrant.json
# Markdown SHA-256:   aa9d69512e3656baf4ba20bc74692cd3e975bcd514faf5ca9c568ca84944a974
# Code AST SHA-256:   c924838f9cd196d55eb932a8b78ce76e9e966cf29cd617165b2a49599ad58d2a
# Verified Classes:   PushWarrantUnconfirmed, TaskHandle
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class PushWarrantUnconfirmed(RuntimeError):
    """Raised when a task's push notification config cannot be read-back-confirmed.

    The Agent Card's capabilities.pushNotifications boolean is a vendor-level
    capability claim, NOT a per-task delivery warrant. Crossing the context-release
    boundary without read-back confirmation produces unobservable (zombie) tasks.
    """


@dataclass
class TaskHandle:
    task_id: str
    url: str
    token: str
    context_released: bool = False
    reconciliation_at: Optional[float] = None
    field(default_factory=dict)


def confirm_push_warrant(
    client,
    handle: TaskHandle,
    expected_duration_s: float,
    read_back_attempts: int = 3,
) -> TaskHandle:
    """Gate context release on read-back-confirmed push config + scheduled reconciliation.

    Must be called BEFORE releasing local execution context. If read-back fails,
    the caller must fall back to polling/streaming or fail explicitly.
    """
    confirmed = None
    for attempt in range(read_back_attempts):
        cfg = client.get_push_notification_config(handle.task_id)
        if cfg is not None and cfg.get("url") == handle.url and cfg.get("token") == handle.token:
            confirmed = cfg
            break
        time.sleep(0.5 * (2 ** attempt))

    if confirmed is None:
        # Do NOT release context. Surface the condition so the caller can fall back.
        raise PushWarrantUnconfirmed(
            f"task {handle.task_id}: push config not read-back-confirmed "
            f"(url={handle.url!r}, token-bound); refusing context release. "
            f"Card capability boolean is insufficient warrant."
        )

    # Only now is context release safe, and only with an independent reconciliation path.
    handle.reconciliation_at = time.monotonic() + max(60.0, 3.0 * expected_duration_s)
    handle.context_released = True
    return handle


def reconcile(client, handle: TaskHandle) -> dict:
    """Idempotent reconciliation: dedupe on (task_id, status.timestamp)."""
    task = client.get_task(handle.task_id)
    if task["status"]["state"] in ("completed", "failed", "canceled"):
        return task
    if handle.reconciliation_at is not None and time.monotonic() >= handle.reconciliation_at:
        raise PushWarrantUnconfirmed(
            f"task {handle.task_id}: still {task['status']['state']!r} past reconciliation "
            f"deadline; push likely dropped by remote tenant policy. Escalate to cancel/re-negotiate."
        )
    return task
