# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-distrust-a-resumed-mcp-sse-stream-after-last-event-id-replay-and-how-does-the-resumption-cursor-diverge-from-th.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-distrust-a-resumed-mcp-sse-stream-after-last-event-id-replay-and-how-does-the-resumption-cursor-diverge-from-th.warrant.json
# Markdown SHA-256:   5867e33b49f8cdcc916b119c064f10237e8b201c15c9308f238b0b2692494066
# Code AST SHA-256:   4fb690a46e7d7c85fce92803013f17b9b79a0f3bb0efa0bf1b81e29d887fc62b
# Verified Classes:   ResumptionIntegrityError, SilentStallError, Event, SessionCursor
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class ResumptionIntegrityError(RuntimeError):
    """Raised when a resumed MCP SSE stream cannot be trusted as a logical continuation."""


class SilentStallError(ResumptionIntegrityError):
    """Raised when the stream is open but no event with a valid next ID arrives within the idle window."""


@dataclass
class Event:
    event_id: int
    payload: dict
    received_at: float = field(default_factory=time.monotonic)


@dataclass
class SessionCursor:
    session_id: str
    # Client-side logical cursor: incremented only after the event's effect is durably applied.
    logical_cursor: int = 0
    # Transport cursor: what we send as Last-Event-ID on reconnect.
    transport_cursor: int = 0
    server_declares_monotonic: bool = False
    server_declares_session_scoped: bool = False
    last_event_at: float = field(default_factory=time.monotonic)


def apply_event(cursor: SessionCursor, event: Event, effect_fn) -> None:
    """Apply an event's semantic effect, then advance the logical cursor.

    The invariant: logical_cursor advances only after effect_fn succeeds. Persisting
    transport_cursor before the effect is applied loses the event on replay.
    """
    effect_fn(event.payload)
    cursor.logical_cursor = event.event_id
    cursor.transport_cursor = event.event_id
    cursor.last_event_at = time.monotonic()


def handle_reconnect(
    cursor: SessionCursor,
    reconnect_response: dict,
    idle_timeout_s: float = 30.0,
) -> None:
    """Validate a reconnect against the resumption integrity invariant.

    reconnect_response is the server's response to the GET with Last-Event-ID.
    Expected keys: session_id, first_event_id (or None if no replay), events (list).
    """
    if not (cursor.server_declares_monotonic and cursor.server_declares_session_scoped):
        raise ResumptionIntegrityError(
            f"server did not declare monotonic+session_scoped resumption for "
            f"session {cursor.session_id}; cannot trust replayed stream"
        )

    if reconnect_response.get("session_id") != cursor.session_id:
        raise ResumptionIntegrityError(
            f"session id changed on reconnect: {cursor.session_id} -> "
            f"{reconnect_response.get('session_id')}; treat as new session"
        )

    events = reconnect_response.get("events", [])
    if not events:
        # No replay frames. Could be a stall or a legitimate no-op. Distinguish by idle timer.
        elapsed = time.monotonic() - cursor.last_event_at
        if elapsed > idle_timeout_s:
            raise SilentStallError(
                f"no events and no heartbeat progress for {elapsed:.1f}s "
                f"past idle window on session {cursor.session_id}"
            )
        return

    expected_next = cursor.logical_cursor + 1
    first_id = events[0].event_id
    if first_id != expected_next:
        raise ResumptionIntegrityError(
            f"replay gap on session {cursor.session_id}: expected first event id "
            f"{expected_next}, got {first_id}; logical state cannot be linearized"
        )

    # Verify strict monotonicity within the replay and no renumbering.
    prev = first_id - 1
    for ev in events:
        if ev.event_id <= prev:
            raise ResumptionIntegrityError(
                f"non-monotonic event id in replay: {ev.event_id} after {prev}"
            )
        prev = ev.event_id


def resume_session(cursor: SessionCursor, reconnect_response: dict, effect_fn) -> None:
    """Full resumption path: validate, then apply events with logical-cursor discipline."""
    handle_reconnect(cursor, reconnect_response)
    for ev in reconnect_response.get("events", []):
        if ev.event_id <= cursor.logical_cursor:
            # Already applied; do not re-apply. This is the idempotency guard.
            continue
        apply_event(cursor, ev, effect_fn)
