# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-an-mcp-session-was-silently-re-homed-during-sse-to-streamable-http-migration-without-losing-resumption-continuity.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-an-mcp-session-was-silently-re-homed-during-sse-to-streamable-http-migration-without-losing-resumption-continuity.warrant.json
# Markdown SHA-256:   42884fecf6810cd0dea732ce7f71c8b477f54defd0d27b8a3e1b48263974038b
# Code AST SHA-256:   1366e36eb83092131ce2c815e0a2a744f418cbafc086603782dc1346bf3c2f6e
# Verified Classes:   SessionRehomedError, ReplayHorizonExceededError, ResumptionState
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

import dataclasses


class SessionRehomedError(RuntimeError):
    """Raised when a resumption stream's event IDs regress, indicating the
    MCP session was silently re-homed to a replica that does not own it."""


class ReplayHorizonExceededError(RuntimeError):
    """Raised when the gap between Last-Event-ID and the first replayed event
    exceeds the server's declared replay horizon (events were evicted)."""


@dataclasses.dataclass
class ResumptionState:
    session_id: str
    last_event_id: int
    replay_horizon: int  # max acceptable gap, declared by server


def verify_resumption(
    state: ResumptionState,
    first_event_id: int | None,
    http_status: int,
) -> None:
    """Validate a streamable-HTTP resumption GET before processing any event.

    Raises on any condition where the stream cannot be trusted as a
    continuation of the stored session.
    """
    if http_status == 404:
        # Correct server behavior: session unknown, client must re-initialize.
        raise SessionRehomedError(
            f"server returned 404 for session {state.session_id!r}; "
            "re-initialize required"
        )

    if http_status != 200:
        raise SessionRehomedError(
            f"unexpected status {http_status} on resumption for "
            f"session {state.session_id!r}"
        )

    if first_event_id is None:
        # 200 with an empty stream: the server accepted the session but has
        # nothing to replay. Cannot prove continuity; treat as re-homed.
        raise SessionRehomedError(
            f"session {state.session_id!r} resumed with empty replay; "
            "continuity unprovable"
        )

    if first_event_id <= state.last_event_id:
        # The core boundary: event IDs must strictly increase per session.
        # A regression means a fresh session is wearing the old ID.
        raise SessionRehomedError(
            f"event id regression on session {state.session_id!r}: "
            f"last_seen={state.last_event_id} first_replayed={first_event_id}"
        )

    gap = first_event_id - state.last_event_id
    if gap > state.replay_horizon:
        raise ReplayHorizonExceededError(
            f"replay gap {gap} exceeds horizon {state.replay_horizon} "
            f"for session {state.session_id!r}; events evicted"
        )


def handle_resumption(state: ResumptionState, first_event_id: int | None,
                      http_status: int) -> ResumptionState:
    verify_resumption(state, first_event_id, http_status)
    # Only reached when continuity is proven.
    return dataclasses.replace(state, last_event_id=first_event_id)
