# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-an-a2a-agent-card-s-pushnotifications-accepted-flag-as-non-transferable-across-task-lifecycle-extensions.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-an-a2a-agent-card-s-pushnotifications-accepted-flag-as-non-transferable-across-task-lifecycle-extensions.warrant.json
# Markdown SHA-256:   19244802d3233f74b22de8dd69d668cfac4e7d3aaea4ffde1ee09193d60f77f0
# Code AST SHA-256:   ab220b310c233c4a7928883486cda64e15028c49da4784b15cf8f1026602b2cc
# Verified Classes:   PushBindingLostError, PushBinding, TaskClient
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class PushBindingLostError(RuntimeError):
    """Raised when a task lifecycle extension invalidates a push binding
    without the server explicitly re-warranting it for the new epoch."""


@dataclass
class PushBinding:
    task_id: str
    push_config_id: str
    epoch: int
    live: bool = True


@dataclass
class TaskClient:
    bindings: dict[str, PushBinding] = field(default_factory=dict)
    fallback_poll_armed: dict[str, bool] = field(default_factory=dict)

    def register(self, task_id: str, push_config_id: str) -> PushBinding:
        b = PushBinding(task_id=task_id, push_config_id=push_config_id, epoch=0)
        self.bindings[task_id] = b
        # Arm fallback poll at registration; disarm ONLY on real callback.
        self.fallback_poll_armed[task_id] = True
        return b

    def extend_lifecycle(self, task_id: str, echoed_config_id: Optional[str]) -> PushBinding:
        """Called on any continuation message/send, resubscribe, or
        input-required round-trip. The card's pushNotifications flag is
        NOT consulted here — only the per-epoch echo is."""
        b = self.bindings.get(task_id)
        if b is None:
            raise PushBindingLostError(f"no binding for task {task_id}")

        # New epoch: old binding is provisionally revoked until echoed back.
        b.live = False
        b.epoch += 1

        if echoed_config_id is None:
            # Server dropped the binding on handler reconstruction.
            # Keep fallback poll armed; do NOT enter callback-only wait.
            self.fallback_poll_armed[task_id] = True
            raise PushBindingLostError(
                f"task {task_id} epoch {b.epoch}: extension turn returned no "
                f"pushConfigId echo; prior binding {b.push_config_id} is dead. "
                f"Fallback poll remains armed."
            )

        if echoed_config_id != b.push_config_id:
            # Server re-keyed the binding; old webhook is orphaned.
            self.fallback_poll_armed[task_id] = True
            raise PushBindingLostError(
                f"task {task_id} epoch {b.epoch}: pushConfigId changed "
                f"{b.push_config_id} -> {echoed_config_id}; old webhook orphaned."
            )

        b.live = True
        return b

    def on_webhook_callback(self, task_id: str, callback_epoch: int) -> None:
        b = self.bindings.get(task_id)
        if b is None or not b.live:
            # Callback for a dead/unknown binding: ignore, do not disarm poll.
            return
        if callback_epoch != b.epoch:
            # Stale-epoch callback from a prior binding; do not disarm poll.
            return
        self.fallback_poll_armed[task_id] = False
