# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a2a-push-notification-completion-against-a-task-s-authoritative-state-when-webhook-delivery-outpaces-runtime-checkpoi.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a2a-push-notification-completion-against-a-task-s-authoritative-state-when-webhook-delivery-outpaces-runtime-checkpoi.warrant.json
# Markdown SHA-256:   0895d5e23b6b4b512336ea0b4c02dfb2871cc7840a896230022717f3517feb19
# Code AST SHA-256:   a7da01d1dbea761dcf8cbb74a2128cf0d0ad4f663304123ee52d08903bd70401
# Verified Classes:   NotificationReconciliationError, TaskRecord, PushNotification, TaskStore, NotificationHandler
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


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


@dataclass
class TaskRecord:
    task_id: str
    state: str
    version: int
    originator: str  # runtime id that issued the task to the sender


@dataclass
class PushNotification:
    task_id: str
    state: str
    sender_runtime: str
    version: int
    received_at: float = field(default_factory=time.monotonic)


class TaskStore:
    """Local durable task store. Writes are versioned and monotonic."""

    def __init__(self):
        self._records: dict[str, TaskRecord] = {}

    def get(self, task_id: str) -> Optional[TaskRecord]:
        return self._records.get(task_id)

    def commit(self, record: TaskRecord) -> None:
        existing = self._records.get(record.task_id)
        if existing is not None and record.version <= existing.version:
            raise NotificationReconciliationError(
                f"non-monotonic commit for {record.task_id}: "
                f"existing v{existing.version} >= new v{record.version}"
            )
        self._records[record.task_id] = record

    def register_push_config(self, task_id: str, callback_url: str) -> None:
        # Invariant: commit-before-advertise. The record MUST exist and be
        # durable before the sender is told where to notify.
        if self.get(task_id) is None:
            raise NotificationReconciliationError(
                f"cannot register push config for {task_id}: no durable record"
            )


class NotificationHandler:
    """Reconciles inbound A2A push notifications against local state."""

    def __init__(self, store: TaskStore, self_runtime_id: str,
                 sender_fetch, buffer_cap: int = 1024):
        self.store = store
        self.self_runtime_id = self_runtime_id
        self.sender_fetch = sender_fetch  # callable(task_id) -> sender snapshot dict
        self.buffer_cap = buffer_cap
        self._buffer: list[PushNotification] = []

    def handle(self, n: PushNotification) -> None:
        local = self.store.get(n.task_id)

        # Case 1: known and local version is current or ahead -> idempotent apply.
        if local is not None and local.version >= n.version:
            if local.state == n.state:
                return  # duplicate delivery; no-op
            self.store.commit(TaskRecord(
                task_id=n.task_id, state=n.state,
                version=local.version + 1, originator=local.originator,
            ))
            return

        # Case 2: known but local is BEHIND -> buffer, read-repair, then apply.
        if local is not None and local.version < n.version:
            self._buffer_notification(n)
            self._read_repair(n.task_id)
            return

        # Case 3: unknown task -> attribution decides, not existence.
        snapshot = self.sender_fetch(n.task_id)
        if snapshot is None:
            # Sender has no such task: spurious / replay / cross-tenant leak.
            raise NotificationReconciliationError(
                f"spurious notification for unknown task {n.task_id} "
                f"from {n.sender_runtime}: sender returned no snapshot"
            )
        if snapshot.get("originator") != self.self_runtime_id:
            # Task exists but was not issued by us: never adopt.
            raise NotificationReconciliationError(
                f"notification for {n.task_id} not attributable to "
                f"{self.self_runtime_id} (originator={snapshot.get('originator')})"
            )
        # Attributable: cold-start reconciliation. Adopt from sender snapshot.
        self.store.commit(TaskRecord(
            task_id=n.task_id,
            state=snapshot["state"],
            version=snapshot["version"],
            originator=self.self_runtime_id,
        ))

    def _buffer_notification(self, n: PushNotification) -> None:
        if len(self._buffer) >= self.buffer_cap:
            # Fail closed: shed oldest, never silently grow.
            self._buffer.pop(0)
        self._buffer.append(n)

    def _read_repair(self, task_id: str) -> None:
        snapshot = self.sender_fetch(task_id)
        if snapshot is None:
            raise NotificationReconciliationError(
                f"read-repair failed: sender has no snapshot for {task_id}"
            )
        self.store.commit(TaskRecord(
            task_id=task_id,
            state=snapshot["state"],
            version=snapshot["version"],
            originator=snapshot["originator"],
        ))
        # Drain any buffered notifications now that local state caught up.
        self._buffer = [b for b in self._buffer if b.task_id != task_id]
