# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-resume-an-mcp-streamable-http-session-after-a-transport-level-reconnect-without-an-event-id-watermark.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-resume-an-mcp-streamable-http-session-after-a-transport-level-reconnect-without-an-event-id-watermark.warrant.json
# Markdown SHA-256:   2a7c7221357adda6f50e8cde40d1d652c3481187dac62e54c12095789d63a81e
# Code AST SHA-256:   814d3372f13593a83ea4c1056c1c2ef49caaefa150f821e2aaec538c564d2aec
# Verified Classes:   ResumptionContiguityError, ReconnectAttempt
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass


class ResumptionContiguityError(RuntimeError):
    """Raised when a resumed MCP SSE stream does not begin at Last-Event-ID + 1."""


@dataclass(frozen=True)
class ReconnectAttempt:
    session_id: str
    last_event_id: int | None          # durable ack, not last-parsed
    first_replayed_event_id: int | None  # None if server returned empty replay
    server_status: int


def validate_resumption(attempt: ReconnectAttempt) -> None:
    """Enforce the contiguity invariant before dispatching any event.

    Must be called on every reconnect. Any violation aborts the stream;
    the caller is responsible for checkpoint re-derivation.
    """
    if attempt.server_status == 404:
        # Session gone: not a resumption, re-initialize.
        raise ResumptionContiguityError(
            f"session {attempt.session_id} expired (404); re-initialize, do not resume"
        )

    if attempt.server_status >= 400:
        # Replay unavailable but session alive: position is lost.
        raise ResumptionContiguityError(
            f"session {attempt.session_id} alive but replay unavailable "
            f"(status={attempt.server_status}); re-derive from checkpoint"
        )

    if attempt.last_event_id is None:
        # No watermark: this is a fresh subscription to a live session.
        raise ResumptionContiguityError(
            f"session {attempt.session_id} resumed without Last-Event-ID; "
            "gap is unobservable, refusing to treat as continuous"
        )

    if attempt.first_replayed_event_id is None:
        # Empty replay is only safe if the server confirms client was at head.
        # We cannot confirm that from the wire alone, so refuse.
        raise ResumptionContiguityError(
            f"session {attempt.session_id} returned empty replay for "
            f"Last-Event-ID={attempt.last_event_id}; cannot prove head position"
        )

    expected = attempt.last_event_id + 1
    if attempt.first_replayed_event_id != expected:
        raise ResumptionContiguityError(
            f"session {attempt.session_id} fast-forwarded: expected first event "
            f"{expected}, got {attempt.first_replayed_event_id}; "
            f"gap of {attempt.first_replayed_event_id - expected} events is unobservable"
        )


def resume_or_recover(attempt: ReconnectAttempt) -> str:
    try:
        validate_resumption(attempt)
    except ResumptionContiguityError as exc:
        # Loud failure: discard live stream, re-derive from durable checkpoint.
        return f"RECOVER: {exc}"
    return "RESUME: stream is contiguous, dispatch may proceed"
