# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-lost-mcp-streamable-http-session-when-sse-reconnection-succeeds-at-the-transport-layer-but-the-server-side-event-cursor.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-lost-mcp-streamable-http-session-when-sse-reconnection-succeeds-at-the-transport-layer-but-the-server-side-event-cursor.warrant.json
# Markdown SHA-256:   b176996d3db80f1cac1f361d1c6e9d646ccf8832e5c2ff1bf7988a275a5745b7
# Code AST SHA-256:   09e494d7b29a022fe6a4e299f5e85114f6fab4de89af2f4ee187a39985dcb222
# Verified Classes:   ResumptionGapError, OutstandingRequest, SessionCursor
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class ResumptionGapError(RuntimeError):
    """Raised when an SSE reconnect resumes at a cursor that is not contiguous
    with the client's last acknowledged event id, indicating lost events."""
    def __init__(self, last_seen: int, first_received: int, session_id: str):
        self.last_seen = last_seen
        self.first_received = first_received
        self.session_id = session_id
        super().__init__(
            f"session {session_id}: reconnect resumed at event {first_received} "
            f"but last acknowledged was {last_seen}; "
            f"{first_received - last_seen - 1} event(s) lost in replay buffer eviction"
        )


@dataclass
class OutstandingRequest:
    rpc_id: str
    method: str
    deadline_ms: int


@dataclass
class SessionCursor:
    session_id: str
    last_event_id: Optional[int] = None
    outstanding: dict[str, OutstandingRequest] = field(default_factory=dict)
    reconnecting: bool = False

    def on_event(self, raw: str) -> dict:
        """Process one SSE event. Enforces contiguity on the first event after
        a reconnect and reconciles the outstanding-request ledger."""
        event_id, payload = self._parse(raw)

        if self.reconnecting:
            if self.last_event_id is not None and event_id != self.last_event_id + 1:
                # Gap detected: do not silently advance the cursor.
                raise ResumptionGapError(
                    last_seen=self.last_event_id,
                    first_received=event_id,
                    session_id=self.session_id,
                )
            self.reconnecting = False

        self.last_event_id = event_id

        # Reconcile: a result/error for an outstanding request clears it.
        if "id" in payload and payload.get("result") is not None or payload.get("error") is not None:
            self.outstanding.pop(str(payload.get("id")), None)

        return payload

    def begin_reconnect(self) -> None:
        """Called before re-establishing the SSE stream. Marks the next event
        as subject to the contiguity check."""
        self.reconnecting = True

    @staticmethod
    def _parse(raw: str) -> tuple[int, dict]:
        event_id = None
        data_lines = []
        for line in raw.splitlines():
            if line.startswith("id:"):
                event_id = int(line[3:].strip())
            elif line.startswith("data:"):
                data_lines.append(line[5:].strip())
        if event_id is None:
            raise ResumptionGapError(-1, -1, "unknown")  # server must emit ids
        return event_id, json.loads("\n".join(data_lines))


def resume_stream(cursor: SessionCursor, reconnect_events: list[str]) -> list[dict]:
    """Drive the post-reconnect event sequence through the contiguity gate."""
    cursor.begin_reconnect()
    processed = []
    for raw in reconnect_events:
        processed.append(cursor.on_event(raw))
    return processed
