# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-a-streamed-mcp-session-after-a-transport-level-reconnect-without-replaying-the-missed-event-window.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-a-streamed-mcp-session-after-a-transport-level-reconnect-without-replaying-the-missed-event-window.warrant.json
# Markdown SHA-256:   3fe03b4f5c8374a1942f1700143e6b59cdf7481636294affd213f3e53fab8a63
# Code AST SHA-256:   100827a539c53031db1c60cf6486786d09a6684edd564223cfefdfc63293703b
# Verified Classes:   StreamResumptionError, EventBuffer
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class StreamResumptionError(RuntimeError):
    """Raised when a client attempts to resume a streamed MCP session
    without a cursor that the server can replay from."""
    pass


@dataclass
class EventBuffer:
    # buffer of (event_id, payload) for semantic outbound frames only;
    # heartbeats are excluded from the ID space by construction.
    events: list = field(default_factory=list)
    head_id: int = 0
    retention: int = 256

    def append(self, payload: dict) -> int:
        self.head_id += 1
        self.events.append((self.head_id, payload))
        if len(self.events) > self.retention:
            self.events.pop(0)
        return self.head_id

    def oldest_available(self) -> int:
        return self.events[0][0] if self.events else self.head_id + 1

    def replay_from(self, cursor: int) -> list:
        if cursor < self.oldest_available() - 1:
            raise StreamResumptionError(
                f"cursor {cursor} predates buffer window "
                f"(oldest available {self.oldest_available()}); "
                f"events in gap are unrecoverable"
            )
        return [p for (eid, p) in self.events if eid > cursor]


def handle_reconnect(
    session_id: str,
    last_event_id: Optional[str],
    buffer: EventBuffer,
    operation_in_flight: bool,
) -> list:
    """
    Decide whether a reconnect is a resumption or a fork.
    Returns replayed events to deliver before going live.
    Raises StreamResumptionError when the client must re-drive instead.
    """
    if not operation_in_flight:
        # no live operation to attach to; clean new stream is fine
        return []

    if last_event_id is None:
        raise StreamResumptionError(
            f"session {session_id}: reconnect during in-flight operation "
            f"without Last-Event-ID; client would silently skip events"
        )

    try:
        cursor = int(last_event_id)
    except ValueError:
        raise StreamResumptionError(
            f"session {session_id}: malformed Last-Event-ID {last_event_id!r}"
        )

    if cursor > buffer.head_id:
        raise StreamResumptionError(
            f"session {session_id}: cursor {cursor} ahead of head "
            f"{buffer.head_id}; client state is corrupt"
        )

    # may raise StreamResumptionError on buffer underrun -> caller re-drives
    return buffer.replay_from(cursor)


def drive_client_reconnect(client, session_id, buffer):
    try:
        gap = handle_reconnect(
            session_id,
            client.last_event_id,
            buffer,
            operation_in_flight=client.pending_tool is not None,
        )
    except StreamResumptionError as e:
        # cannot prove continuity: abandon and re-drive with idempotency key
        client.redrive_with_idempotency_key(reason=str(e))
        return
    for event in gap:
        client.apply_event(event)  # dedupe by event id inside apply_event
    client.go_live()
