# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-streamable-http-session-after-sse-to-streamable-migration-without-reconciling-the-last-event-id-namespace.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-streamable-http-session-after-sse-to-streamable-migration-without-reconciling-the-last-event-id-namespace.warrant.json
# Markdown SHA-256:   1cb4180cd9ca510403677522071291cec5b8eb292ee8d398ef83f2405944874e
# Code AST SHA-256:   51d99a21ce97840298ce337a0a3c5b97d1e4bdc126045df876d58a07ffda9ba5
# Verified Classes:   StreamResumeError, PersistedCursor
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional, Tuple


class StreamResumeError(RuntimeError):
    """Raised when a Last-Event-ID resume cannot be safely honored."""
    pass


@dataclass(frozen=True)
class PersistedCursor:
    transport_kind: str          # "sse" | "streamable-http"
    session_id: str
    event_id: str
    generation: int              # bumped on every successful initialize


def plan_reconnect(
    persisted: Optional[PersistedCursor],
    current_transport_kind: str,
    current_session_id: str,
    current_generation: int,
) -> Tuple[str, Optional[str]]:
    """
    Returns (action, last_event_id) where action is "resume" or "reinitialize".
    """
    if persisted is None:
        return ("reinitialize", None)

    # Transport migration boundary: never resume across transport kinds.
    if persisted.transport_kind != current_transport_kind:
        return ("reinitialize", None)

    # Session boundary: a new Mcp-Session-Id invalidates the event namespace.
    if persisted.session_id != current_session_id:
        return ("reinitialize", None)

    # Generation boundary: catches server-side session reuse after expiry.
    if persisted.generation != current_generation:
        return ("reinitialize", None)

    return ("resume", persisted.event_id)


def handle_resume_response(status: int, persisted: PersistedCursor) -> None:
    if status in (400, 404):
        # Server rejected the resume: unknown event or expired session.
        # This is terminal for the resume path; caller must re-initialize.
        raise StreamResumeError(
            f"resume rejected (status={status}) for session "
            f"{persisted.session_id} event {persisted.event_id}; "
            f"falling back to initialize"
        )
    if status != 200:
        raise StreamResumeError(f"unexpected resume status {status}")
