# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-its-mcp-session-identity-when-a-multiplexed-http-stream-resumes-across-a-transport-interruption.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-its-mcp-session-identity-when-a-multiplexed-http-stream-resumes-across-a-transport-interruption.warrant.json
# Markdown SHA-256:   68d1feb6b7b91504b14bf7b3160f555d1d92dc65c0c55252e79e19d37b04506c
# Code AST SHA-256:   f321fe446d99a3b454de03c5d9130334d74c7a11bd46ad654b8fc573ff37cdc7
# Verified Classes:   SessionReplayMismatch, Cursor, ReplayStore
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class SessionReplayMismatch(RuntimeError):
    """Raised when a resumable stream cursor cannot be safely bound to the presenting session."""
    pass


@dataclass(frozen=True)
class Cursor:
    session_id: str
    seq: int

    def encode(self) -> str:
        return f"{self.session_id}:{self.seq}"

    @staticmethod
    def decode(raw: str) -> "Cursor":
        sid, _, seq = raw.rpartition(":")
        if not sid or not seq.isdigit():
            raise SessionReplayMismatch(f"malformed Last-Event-ID {raw!r}")
        return Cursor(session_id=sid, seq=int(seq))


class ReplayStore:
    def __init__(self, session_ttl_events: int = 5000) -> None:
        self._events: dict[str, list[str]] = {}   # session_id -> payloads
        self._reaped: set[str] = set()
        self._ttl = session_ttl_events

    def mint(self, session_id: str, payload: str) -> Cursor:
        if session_id in self._reaped:
            raise SessionReplayMismatch(f"session {session_id} reaped; cannot mint")
        buf = self._events.setdefault(session_id, [])
        buf.append(payload)
        return Cursor(session_id=session_id, seq=len(buf))

    def reap(self, session_id: str) -> None:
        # Tombstone: keep the id so late cursors are refused, drop payloads.
        self._reaped.add(session_id)
        self._events.pop(session_id, None)

    def resume(self, presenting_session: str, last_event_id: Optional[str]) -> list[str]:
        if last_event_id is None:
            return []
        cursor = Cursor.decode(last_event_id)

        # The invariant: cursor must belong to the session presenting it.
        if cursor.session_id != presenting_session:
            raise SessionReplayMismatch(
                f"cursor {cursor.encode()} minted by {cursor.session_id!r} "
                f"presented by {presenting_session!r}"
            )
        if cursor.session_id in self._reaped:
            raise SessionReplayMismatch(
                f"session {cursor.session_id!r} reaped; refusing cross-reap replay"
            )

        buf = self._events.get(cursor.session_id, [])
        if cursor.seq > len(buf):
            raise SessionReplayMismatch(
                f"cursor {cursor.encode()} beyond retained window {len(buf)}"
            )
        return buf[cursor.seq:]


def handle_reconnect(store: ReplayStore, session_id: str, last_event_id: Optional[str]) -> list[str]:
    try:
        return store.resume(session_id, last_event_id)
    except SessionReplayMismatch as exc:
        # Terminal: force client to reinitialize rather than transplant state.
        raise SessionReplayMismatch(f"reinitialize required: {exc}") from exc
