# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-an-mcp-session-id-as-non-resumable-after-sse-to-streamable-http-migration.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-an-mcp-session-id-as-non-resumable-after-sse-to-streamable-http-migration.warrant.json
# Markdown SHA-256:   a24b520a28b216848d70b1bccd3260910925a1278e3cd624501406309b76042d
# Code AST SHA-256:   5e729939d1aa94becdaafa33bf7625812d10c52ddd13045da7b6d67b6abc4ce4
# Verified Classes:   NonResumableSessionError, TransportGeneration, SessionHandle, InFlightRequest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from enum import Enum
from typing import Optional


class NonResumableSessionError(RuntimeError):
    """Raised when a client attempts to resume an MCP request across a
    transport boundary without a server-issued resumption token."""


class TransportGeneration(Enum):
    HTTP_SSE = "http+sse"
    STREAMABLE_HTTP = "streamable-http"


@dataclass(frozen=True)
class SessionHandle:
    session_id: str
    generation: TransportGeneration
    protocol_version: str
    # Server-advertised capability flag; must be True to honor a request ledger.
    supports_request_ledger: bool


@dataclass(frozen=True)
class InFlightRequest:
    jsonrpc_id: str
    tool_name: str
    idempotent: bool
    last_fully_received_response: Optional[dict]
    # Proof the server will not double-execute: an idempotency key the server
    # has acknowledged, NOT the SSE Last-Event-ID.
    resumption_token: Optional[str]


def assert_resumable(session: SessionHandle, request: InFlightRequest) -> None:
    """Enforce the resumption invariant before re-issuing a request.

    Resume is permitted only when the session and the request belong to the
    same transport generation, the server advertises a request ledger, and
    the client holds a server-acknowledged resumption token.
    """
    if not session.supports_request_ledger:
        raise NonResumableSessionError(
            f"session {session.session_id} ({session.generation.value}) "
            "does not advertise a request ledger; resume would risk "
            "duplicate execution"
        )

    if request.resumption_token is None:
        raise NonResumableSessionError(
            f"request {request.jsonrpc_id} for tool {request.tool_name!r} "
            "has no server-acknowledged resumption token; SSE Last-Event-ID "
            "is not a valid cursor for Streamable HTTP"
        )

    if (
        request.last_fully_received_response is None
        and not request.idempotent
    ):
        raise NonResumableSessionError(
            f"non-idempotent tool {request.tool_name!r} has no completed "
            "response and no proof of non-execution; failing closed to "
            "avoid silent duplicate side effects"
        )


def plan_recovery(
    session: SessionHandle,
    request: InFlightRequest,
    server_returned_404: bool,
) -> str:
    """Return 'resume' or 'reinitialize' per the decision boundary."""
    if server_returned_404:
        # Spec: 404 on session means terminated. Do NOT reuse the ID.
        return "reinitialize"

    if session.generation is TransportGeneration.HTTP_SSE:
        # Legacy transport: SSE replay is valid, but only within SSE.
        return "resume"

    try:
        assert_resumable(session, request)
    except NonResumableSessionError:
        return "reinitialize"
    return "resume"


def fingerprint(session: SessionHandle, request: InFlightRequest) -> str:
    payload = json.dumps(
        {
            "sid": session.session_id,
            "gen": session.generation.value,
            "rid": request.jsonrpc_id,
            "tok": request.resumption_token,
        },
        sort_keys=True,
    )
    return hashlib.sha256(payload.encode()).hexdigest()[:16]
