# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-sse-last-event-id-resumption-as-a-replay-consistency-problem-rather-than-a-transport-reconnect-problem.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-sse-last-event-id-resumption-as-a-replay-consistency-problem-rather-than-a-transport-reconnect-problem.warrant.json
# Markdown SHA-256:   7de98d6cd332f8916ecfe6aa800238e3c276adb2ce5fd62077311f6ffdddbbad
# Code AST SHA-256:   143c54c8e17c3d00f82ebb79956911fd685e71ccfd279c805ad57aae4cf8ebae
# Verified Classes:   ReplayConsistencyError, DispatchRecord, StreamCursor
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class ReplayConsistencyError(RuntimeError):
    """Raised when Last-Event-ID replay cannot be proven safe."""


@dataclass
class DispatchRecord:
    event_id: int
    idempotency_key: str
    committed: bool = False


@dataclass
class StreamCursor:
    last_committed_event_id: int = 0
    ledger: Dict[int, DispatchRecord] = field(default_factory=dict)
    retention_floor: int = 0

    def record_dispatch(self, event_id: int, idempotency_key: str) -> None:
        self.ledger[event_id] = DispatchRecord(event_id, idempotency_key)

    def commit(self, event_id: int) -> None:
        rec = self.ledger.get(event_id)
        if rec is None:
            raise ReplayConsistencyError(
                f"commit for unknown event {event_id}; ledger desynchronized"
            )
        rec.committed = True
        # Advance cursor only past contiguous committed events.
        nxt = self.last_committed_event_id + 1
        while nxt in self.ledger and self.ledger[nxt].committed:
            self.last_committed_event_id = nxt
            nxt += 1

    def plan_resume(self, server_head: int, first_replayed_id: Optional[int]) -> int:
        """Return a safe Last-Event-ID, or raise if replay cannot be proven safe."""
        if self.last_committed_event_id < self.retention_floor:
            raise ReplayConsistencyError(
                f"cursor {self.last_committed_event_id} below retention floor "
                f"{self.retention_floor}; session must be re-established, not replayed"
            )
        in_flight = [
            r for r in self.ledger.values()
            if not r.committed and r.event_id > self.last_committed_event_id
        ]
        if in_flight:
            # Cannot safely replay past an uncommitted dispatch without reconciliation.
            raise ReplayConsistencyError(
                "in-flight dispatches present at cursor: "
                + ", ".join(str(r.event_id) for r in in_flight)
                + "; reconcile via idempotency key before resuming stream"
            )
        if first_replayed_id is not None and first_replayed_id > self.last_committed_event_id + 1:
            raise ReplayConsistencyError(
                f"replay gap: server resumed at {first_replayed_id} but cursor is "
                f"{self.last_committed_event_id}; events were pruned"
            )
        return self.last_committed_event_id


def handle_replayed_event(cursor: StreamCursor, event_id: int, idempotency_key: str) -> str:
    existing = cursor.ledger.get(event_id)
    if existing is not None and existing.committed:
        return "suppressed-duplicate"
    if existing is not None and not existing.committed:
        # Re-delivery of an in-flight dispatch: must reconcile, not re-execute.
        return f"reconcile:{existing.idempotency_key}"
    cursor.record_dispatch(event_id, idempotency_key)
    return "execute"
