# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-re-signs-an-a2a-push-notification-with-a-rotated-key-mid-task-webhook-replay-divergence-across-the-task-state-machine.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-re-signs-an-a2a-push-notification-with-a-rotated-key-mid-task-webhook-replay-divergence-across-the-task-state-machine.warrant.json
# Markdown SHA-256:   ce95975a8ea6af6a2854f59c3137535ef3b176ea128397c846c7f8d12474bf1b
# Code AST SHA-256:   bc1c75d3cba3172d353bdcdb7580c7b2a6e323a9d4a7f57abfd625dbcfed7c09
# Verified Classes:   PushNotificationReplayError, Notification, TaskLedger, PushReceiver
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class PushNotificationReplayError(RuntimeError):
    """Raised when a replayed notification cannot be reconciled to task state."""
    pass


@dataclass
class Notification:
    task_id: str
    sequence: int
    kid: str
    signature: str
    state: str


@dataclass
class TaskLedger:
    task_id: str
    last_sequence: int = -1
    terminal: bool = False
    accepted_kids: dict = field(default_factory=dict)  # kid -> emission_epoch


class PushReceiver:
    def __init__(self, key_history: dict, current_kid: str):
        # key_history: kid -> public key, retained across rotations
        self.key_history = key_history
        self.current_kid = current_kid
        self.ledgers: dict[str, TaskLedger] = {}

    def _resolve_key(self, n: Notification) -> Optional[str]:
        # Resolve against emission-time key history, NOT the live card.
        return self.key_history.get(n.kid)

    def ingest(self, n: Notification) -> str:
        ledger = self.ledgers.setdefault(n.task_id, TaskLedger(n.task_id))

        if ledger.terminal:
            raise PushNotificationReplayError(
                f"notification for terminal task {n.task_id} seq={n.sequence}"
            )

        key = self._resolve_key(n)
        if key is None:
            # Unknown kid: quarantine, do not reject. Reconcile via tasks/get.
            return "quarantine"

        if n.sequence != ledger.last_sequence + 1:
            # Sequence gap: reject and re-fetch authoritative task object.
            raise PushNotificationReplayError(
                f"sequence gap for {n.task_id}: expected "
                f"{ledger.last_sequence + 1}, got {n.sequence}"
            )

        # Signature check is deferred to reconciliation for quarantined items;
        # here we only advance on contiguous, key-resolvable notifications.
        ledger.last_sequence = n.sequence
        ledger.accepted_kids[n.kid] = time.time()
        if n.state in ("completed", "failed", "canceled"):
            ledger.terminal = True
        return "accepted"


def replay_backlog(receiver: PushReceiver, backlog: list[Notification]) -> dict:
    results = {}
    for n in sorted(backlog, key=lambda x: x.sequence):
        try:
            results[n.sequence] = receiver.ingest(n)
        except PushNotificationReplayError as e:
            # Do NOT mark task failed on signature/key resolution failure.
            results[n.sequence] = f"reconcile:{e}"
    return results
