# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-resumable-mcp-session-has-migrated-from-sse-to-streamable-http-under-a-stale-oauth-2-1-resource-server-binding.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-resumable-mcp-session-has-migrated-from-sse-to-streamable-http-under-a-stale-oauth-2-1-resource-server-binding.warrant.json
# Markdown SHA-256:   f5e3ff44692759acc1278c01c196398e0b7500fecda54797f426289ffa4dab2d
# Code AST SHA-256:   94ca254f594ca5bca934c643f6c35931a9f31f7a83edfd30bb4e9344159524b7
# Verified Classes:   SessionMigrationError, ResumptionResponse
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass


class SessionMigrationError(RuntimeError):
    """Raised when a resumable SSE session crosses into streamable-HTTP
    without re-deriving the OAuth 2.1 resource binding."""
    pass


@dataclass
class ResumptionResponse:
    status: int
    content_type: str
    has_session_id: bool
    www_authenticate: str | None
    token_resource_claim: str | None


def resource_indicator_for(endpoint_url: str) -> str:
    # RFC 8707: exact string match, path-sensitive. Strip query/fragment.
    return re.sub(r"[?#].*$", "", endpoint_url)


def validate_resumption(
    request_last_event_id: str | None,
    endpoint_url: str,
    resp: ResumptionResponse,
) -> None:
    is_sse = resp.content_type.startswith("text/event-stream")

    # Migration signal: cursor presented, but server answered on a non-SSE transport.
    if request_last_event_id is not None and not is_sse:
        if resp.status == 401 and resp.www_authenticate and "invalid_token" in resp.www_authenticate:
            expected = resource_indicator_for(endpoint_url)
            if resp.token_resource_claim != expected:
                raise SessionMigrationError(
                    f"transport migrated SSE->streamable-HTTP at {endpoint_url}; "
                    f"Last-Event-ID {request_last_event_id} is void and token "
                    f"resource claim {resp.token_resource_claim!r} != {expected!r}. "
                    f"Do NOT re-auth-retry; re-derive resource indicator and "
                    f"start a fresh Mcp-Session-Id handshake."
                )
        if resp.status == 200 and resp.has_session_id:
            raise SessionMigrationError(
                f"server accepted cursor {request_last_event_id} but issued a new "
                f"Mcp-Session-Id on non-SSE content-type {resp.content_type!r}; "
                f"events between cursor and new session are unrecoverable. "
                f"Invalidate cursor and re-synchronize state explicitly."
            )
    return


def resume_session(last_event_id, endpoint_url, resp):
    validate_resumption(last_event_id, endpoint_url, resp)
    return "resumed"
