# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-resumed-mcp-streamable-http-sse-session-when-the-server-s-last-event-id-cursor-and-the-client-s-replay-buffer-have.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-resumed-mcp-streamable-http-sse-session-when-the-server-s-last-event-id-cursor-and-the-client-s-replay-buffer-have.warrant.json
# Markdown SHA-256:   2df37c88e006bc662f4958ad56b3616b0b75d67fbfef199c6cd71278aacc3bad
# Code AST SHA-256:   2abecf2970e5a11a318a85ed7f1e9f041e11f6b8b11c3c85af4c84a4663319da
# Verified Classes:   StreamResyncRequired, ResumableSSEClient
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class StreamResyncRequired(RuntimeError):
    """Raised when a resumed SSE stream cannot be proven contiguous with client state."""
    pass


@dataclass
class ResumableSSEClient:
    # Cursor advanced ONLY after a handler returns successfully.
    last_dispatched_id: Optional[int] = None
    # Highest id for which bytes were received (may exceed last_dispatched_id).
    last_received_id: Optional[int] = None
    pending: list = field(default_factory=list)
    server_replay_window: Optional[int] = None  # None = unknown/unbounded

    def on_frame_received(self, event_id: int, payload: dict) -> None:
        # Receipt does NOT advance the dispatch cursor.
        self.last_received_id = event_id
        self.pending.append((event_id, payload))

    def dispatch_pending(self, handler) -> None:
        # Only here does the cursor move — after the handler succeeds.
        while self.pending:
            event_id, payload = self.pending[0]
            handler(payload)  # may raise; if so, cursor stays put
            self.pending.pop(0)
            self.last_dispatched_id = event_id

    def resume(self, reconnect_first_id: int) -> None:
        """Called with the first event id the server streams after reattach."""
        if self.last_dispatched_id is None:
            # Cold start: no prior state, accept the stream as-is.
            return

        expected_next = self.last_dispatched_id + 1
        if reconnect_first_id == expected_next:
            return  # contiguous, safe to continue incrementally

        if reconnect_first_id > expected_next:
            gap = reconnect_first_id - expected_next
            # If a replay window is advertised and the gap fits, the server
            # owes us a replay; if it resumed past it, state is lost.
            if self.server_replay_window is not None and gap > self.server_replay_window:
                raise StreamResyncRequired(
                    f"resume skipped {gap} events (window={self.server_replay_window}); "
                    f"cursor {self.last_dispatched_id} -> {reconnect_first_id}; "
                    "re-fetch tools/list and resources before further calls"
                )
            # Unknown window or unadvertised truncation: cannot prove contiguity.
            raise StreamResyncRequired(
                f"non-contiguous resume: expected {expected_next}, got {reconnect_first_id}; "
                "server may have truncated replay log"
            )

        if reconnect_first_id <= self.last_dispatched_id:
            # Server replayed already-dispatched events; drop duplicates.
            self.pending = [
                (eid, p) for (eid, p) in self.pending
                if eid > self.last_dispatched_id
            ]
            return


def reattach(client: ResumableSSEClient, reconnect_first_id: int, resync) -> None:
    try:
        client.resume(reconnect_first_id)
    except StreamResyncRequired as exc:
        # Mandatory: abandon incremental state, re-sync authoritative state.
        resync()  # e.g. tools/list + resources/read
        client.pending.clear()
        client.last_dispatched_id = reconnect_first_id - 1
        raise StreamResyncRequired(f"resynced after: {exc}") from exc
