# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-sse-stream-across-a-mid-flight-transport-upgrade-to-websocket.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-sse-stream-across-a-mid-flight-transport-upgrade-to-websocket.warrant.json
# Markdown SHA-256:   51c59a3998b88d49333b836213e38a2a3a309826a1416d550e7580951981e8ed
# Code AST SHA-256:   361b9c4bbc1a91dd55a820878704c3306c2f66469d4b0bdb142113bbcb727513
# Verified Classes:   StreamContinuityError, Frame
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from __future__ import annotations

import dataclasses
from typing import Optional


class StreamContinuityError(RuntimeError):
    """Raised when a resumed/upgraded MCP stream fails to prove cursor continuity.

    This is a fail-closed signal: the caller must NOT continue on the stream
    and must escalate to cold restart (re-initialize the MCP session).
    """


@dataclasses.dataclass(frozen=True)
class Frame:
    event_id: int
    transport: str  # "sse" | "ws"
    payload: dict


def verify_upgrade_continuity(
    last_sse_event_id: int,
    first_ws_frame: Frame,
    *,
    replay_complete_id: Optional[int] = None,
) -> int:
    """Verify that a WebSocket upgrade continued the SSE event log.

    Returns the new cursor (the highest event id proven contiguous).
    Raises StreamContinuityError if continuity cannot be proven.

    Contract:
      - If the server sent an explicit replay_complete control frame covering
        [last_sse_event_id + 1, replay_complete_id], the first live ws frame
        must be > replay_complete_id.
      - Otherwise, the first ws frame must be exactly last_sse_event_id + 1.
    """
    if first_ws_frame.transport != "ws":
        raise StreamContinuityError(
            f"expected ws frame at upgrade boundary, got {first_ws_frame.transport!r}"
        )

    if replay_complete_id is not None:
        if replay_complete_id < last_sse_event_id:
            raise StreamContinuityError(
                f"replay_complete_id {replay_complete_id} precedes client cursor "
                f"{last_sse_event_id}; server replayed from the wrong position"
            )
        if first_ws_frame.event_id <= replay_complete_id:
            raise StreamContinuityError(
                f"first live ws frame id {first_ws_frame.event_id} falls inside "
                f"replayed range (<= {replay_complete_id}); duplicate delivery risk"
            )
        return first_ws_frame.event_id

    # No explicit replay control frame: require exact +1 continuation.
    expected = last_sse_event_id + 1
    if first_ws_frame.event_id != expected:
        raise StreamContinuityError(
            f"cursor discontinuity across upgrade: expected event {expected}, "
            f"got {first_ws_frame.event_id} "
            f"(delta={first_ws_frame.event_id - expected}); "
            "server likely reset its sequence on ws handoff"
        )
    return first_ws_frame.event_id


def resume_stream(
    client,
    last_event_id: int,
    *,
    allow_upgrade: bool = True,
) -> int:
    """Attempt resumption; fail closed to cold restart on continuity violation."""
    try:
        stream = client.reconnect(last_event_id=last_event_id, allow_upgrade=allow_upgrade)
        if stream.transport == "ws":
            first = stream.next_frame()
            return verify_upgrade_continuity(last_event_id, first)
        return last_event_id  # plain SSE resume; server owns replay
    except StreamContinuityError:
        # Loud, typed failure. Caller must cold-restart, not continue.
        raise
    except Exception as exc:  # transport-level failure, still fail closed
        raise StreamContinuityError(
            f"resumption failed at transport layer: {exc!r}"
        ) from exc
