# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-the-last-event-id-on-a-streamable-mcp-session-as-a-resumption-cursor-rather-than-a-replay-token-when-the-server-has-alrea.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-the-last-event-id-on-a-streamable-mcp-session-as-a-resumption-cursor-rather-than-a-replay-token-when-the-server-has-alrea.warrant.json
# Markdown SHA-256:   c0c3622205af3a9074a00e5e25a3db8e8ea722c9f1506b1c1b0ef20962538cba
# Code AST SHA-256:   20bcf6d3521d7ee965af272f5e7bc57852160d602e15a5a19e5a59f67ab3dce5
# Verified Classes:   CursorProvenanceError, Cursor, StreamableSessionCursor
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class CursorProvenanceError(RuntimeError):
    """Raised when a resumption cursor cannot be provenanced to the emitter
    that minted it, or when a replayed event collides across epochs."""


@dataclass(frozen=True)
class Cursor:
    epoch: int
    last_id: int


class StreamableSessionCursor:
    def __init__(self) -> None:
        self._epoch = 0
        self._cursor: Optional[Cursor] = None
        self._applied: dict[tuple[int, int], str] = {}  # (epoch, id) -> effect key

    def observe_transport_transition(self) -> None:
        # SSE emitter torn down, or POST-serviced path entered, or new emitter.
        self._epoch += 1

    def resumption_header(self) -> dict[str, str]:
        if self._cursor is None:
            return {}
        if self._cursor.epoch != self._epoch:
            # Cursor minted by a different emitter; do not present it as a
            # replay token. Cold-start reconciliation is required instead.
            return {"X-Applied-Cursor-Source": f"stale-epoch:{self._cursor.epoch}"}
        return {
            "Last-Event-ID": str(self._cursor.last_id),
            "X-Applied-Cursor-Source": f"sse:{self._epoch}",
        }

    def apply_event(self, event_epoch: int, event_id: int, effect_key: str) -> None:
        if event_epoch != self._epoch:
            raise CursorProvenanceError(
                f"event id={event_id} claims epoch={event_epoch} but current "
                f"epoch={self._epoch}; buffer was swapped across upgrade boundary"
            )
        key = (event_epoch, event_id)
        if key in self._applied:
            if self._applied[key] != effect_key:
                raise CursorProvenanceError(
                    f"event id={event_id} re-applied with different effect "
                    f"{effect_key!r} (was {self._applied[key]!r}); cross-buffer "
                    f"ID collision"
                )
            return  # idempotent duplicate
        self._applied[key] = effect_key
        if self._cursor is None or event_id > self._cursor.last_id:
            self._cursor = Cursor(epoch=event_epoch, last_id=event_id)

    def advance_after_cold_start(self, reconciled_epoch: int) -> None:
        # After a cold-start reconciliation, the cursor is re-anchored to the
        # current epoch only once authoritative state has been re-fetched.
        if reconciled_epoch != self._epoch:
            raise CursorProvenanceError(
                f"cold-start reconciliation epoch {reconciled_epoch} does not "
                f"match current epoch {self._epoch}"
            )
        self._cursor = Cursor(epoch=reconciled_epoch, last_id=0)
