# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-streamable-session-resumption-against-sse-last-event-id-replay-when-an-mcp-server-behind-an-http-native-transport-has.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-streamable-session-resumption-against-sse-last-event-id-replay-when-an-mcp-server-behind-an-http-native-transport-has.warrant.json
# Markdown SHA-256:   b5b88a6a6b80b61b7228cae86c1d262513a96aade2cba4f4b62667d2eab769a6
# Code AST SHA-256:   1d8802d74160f79bed242bff4dd5e932443e20c5e24f4c34f9ea0d2b6560bf38
# Verified Classes:   CursorGapError, UnresumableSessionError, ResumptionState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass


class CursorGapError(RuntimeError):
    """Raised when a resumed SSE stream does not continue from the acknowledged cursor."""


class UnresumableSessionError(RuntimeError):
    """Raised when the server cannot map Last-Event-ID to a replayable position."""


@dataclass
class ResumptionState:
    session_id: str
    last_acknowledged_id: int
    operation_is_idempotent: bool


def validate_resumption(
    state: ResumptionState,
    first_received_id: int | None,
    server_status: int,
    server_declared_gap: bool,
) -> None:
    # Server could not map the cursor to its retained log.
    if server_status in (404, 409) and not server_declared_gap:
        # Ambiguous: could be expired session OR evicted cursor. Fail closed.
        if not state.operation_is_idempotent:
            raise UnresumableSessionError(
                f"session {state.session_id}: cursor {state.last_acknowledged_id} "
                f"unmappable (status {server_status}); non-idempotent op must not restart blindly"
            )
        return

    if server_declared_gap:
        if not state.operation_is_idempotent:
            raise CursorGapError(
                f"session {state.session_id}: server declared gap after "
                f"{state.last_acknowledged_id}; refusing to merge non-idempotent result"
            )
        return

    if first_received_id is None:
        raise CursorGapError(
            f"session {state.session_id}: resumption stream carried no event id"
        )

    expected = state.last_acknowledged_id + 1
    if first_received_id != expected:
        # Forward jump == silent gap. Never paper over it.
        raise CursorGapError(
            f"session {state.session_id}: expected first id {expected}, "
            f"got {first_received_id} (gap of {first_received_id - expected} events)"
        )


def resume_stream(state: ResumptionState, response: dict) -> list[int]:
    validate_resumption(
        state,
        first_received_id=response.get("first_event_id"),
        server_status=response.get("status", 200),
        server_declared_gap=response.get("declared_gap", False),
    )
    return response.get("event_ids", [])
