# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a2a-push-notification-replay-against-a-resuming-task-s-checkpoint-when-webhook-delivery-is-at-least-once-but-task-sta.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a2a-push-notification-replay-against-a-resuming-task-s-checkpoint-when-webhook-delivery-is-at-least-once-but-task-sta.warrant.json
# Markdown SHA-256:   5feba62816e66231bec891638c906958a1659c200d677c0fcd685fe2ae42bc79
# Code AST SHA-256:   a88a450ca51b2ecbb38f9954581661b1828fea253ad25f76b4f5899ff8e490a1
# Verified Classes:   NotificationReconciliationError, TaskState, Checkpoint, Notification, AuthoritativeTask, NotificationHandler
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class NotificationReconciliationError(RuntimeError):
    """Raised when a push notification cannot be safely reconciled against local checkpoint state."""
    pass


class TaskState(Enum):
    RUNNING = "RUNNING"
    COMPLETED = "COMPLETED"
    FAILED = "FAILED"
    CANCELED = "CANCELED"


TERMINAL = {TaskState.COMPLETED, TaskState.FAILED, TaskState.CANCELED}


@dataclass
class Checkpoint:
    task_id: str
    version: int
    state: TaskState = TaskState.RUNNING


@dataclass
class Notification:
    task_id: str
    task_version: int


@dataclass
class AuthoritativeTask:
    task_id: str
    version: int
    state: TaskState


class NotificationHandler:
    def __init__(
        self,
        fetch_authoritative: Callable[[str], AuthoritativeTask],
        resume: Callable[[Checkpoint, AuthoritativeTask], None],
        replication_budget_s: float = 5.0,
        poll_interval_s: float = 0.25,
    ):
        self._fetch = fetch_authoritative
        self._resume = resume
        self._budget = replication_budget_s
        self._poll = poll_interval_s
        self._locks: dict[str, bool] = {}

    def _acquire(self, task_id: str) -> bool:
        if self._locks.get(task_id):
            return False
        self._locks[task_id] = True
        return True

    def _release(self, task_id: str) -> None:
        self._locks[task_id] = False

    def handle(self, cp: Checkpoint, note: Notification) -> str:
        if note.task_id != cp.task_id:
            raise NotificationReconciliationError(
                f"notification task_id {note.task_id} != checkpoint {cp.task_id}"
            )

        # Terminal is absorbing: acknowledge and drop, never resume.
        if cp.state in TERMINAL:
            return "dropped_terminal"

        # Replay / out-of-order: notification carries no new information.
        if note.task_version <= cp.version:
            return "dropped_stale_notification"

        if not self._acquire(cp.task_id):
            # Concurrent duplicate delivery; single-flight rejects the loser.
            return "dropped_concurrent"

        try:
            deadline = time.monotonic() + self._budget
            while True:
                fetched = self._fetch(cp.task_id)

                if fetched.state in TERMINAL and fetched.version <= cp.version:
                    raise NotificationReconciliationError(
                        f"emitter reports terminal state at version {fetched.version} "
                        f"not ahead of checkpoint {cp.version}; state store inconsistent"
                    )

                if fetched.version > cp.version:
                    # Atomic advance + resume.
                    self._resume(cp, fetched)
                    cp.version = fetched.version
                    cp.state = fetched.state
                    return "resumed"

                # fetched.version <= cp.version: stale read, must re-poll, not drop.
                if time.monotonic() >= deadline:
                    raise NotificationReconciliationError(
                        f"stale read persisted past replication budget for task "
                        f"{cp.task_id}: notification v{note.task_version}, "
                        f"checkpoint v{cp.version}, fetched v{fetched.version}"
                    )
                time.sleep(self._poll)
        finally:
            self._release(cp.task_id)
