# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-sse-to-streamable-http-migration-as-a-session-boundary-rather-than-a-transport-upgrade.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-sse-to-streamable-http-migration-as-a-session-boundary-rather-than-a-transport-upgrade.warrant.json
# Markdown SHA-256:   c4c62670aff3153a50ddcdb8ca3eff7ccc3406c4e31fd396e0e6eb8387726aa4
# Code AST SHA-256:   ee582196274292a828257bcec9ef2463001d5133dd6e1a62dbcd5cfefa85fb28
# Verified Classes:   SessionMigrationBoundaryError, SessionTuple
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class SessionMigrationBoundaryError(RuntimeError):
    """Raised when a transport migration cannot be treated as a transparent upgrade."""
    pass


@dataclass(frozen=True)
class SessionTuple:
    session_id: str
    endpoint_uri: str
    event_cursor: Optional[int]
    resource_indicator: str

    def fingerprint(self) -> str:
        raw = f"{self.session_id}|{self.endpoint_uri}|{self.event_cursor}|{self.resource_indicator}"
        return hashlib.sha256(raw.encode()).hexdigest()[:16]


def classify_migration(
    before: SessionTuple,
    after: SessionTuple,
    *,
    server_preserves_old_session: bool,
    cursor_is_session_namespaced: bool,
    token_resource_matches_new_uri: bool,
) -> str:
    """
    Returns one of: 'transparent', 'boundary'.
    Raises SessionMigrationBoundaryError if the caller attempts to resume
    across a boundary without re-initialization.
    """
    if before.session_id != after.session_id and not server_preserves_old_session:
        # Old session is gone; any Last-Event-ID replay targets a dead namespace.
        return "boundary"

    if before.event_cursor is not None and not cursor_is_session_namespaced:
        # Cursor aliasing risk: S1:4417 may not mean S2:4417.
        return "boundary"

    if before.endpoint_uri != after.endpoint_uri and not token_resource_matches_new_uri:
        # RFC 8707 resource binding broken; token will be rejected or downgraded.
        return "boundary"

    return "transparent"


def resume_or_reinitialize(
    before: SessionTuple,
    after: SessionTuple,
    *,
    server_preserves_old_session: bool,
    cursor_is_session_namespaced: bool,
    token_resource_matches_new_uri: bool,
    pending_tool_call: Optional[str] = None,
) -> str:
    verdict = classify_migration(
        before,
        after,
        server_preserves_old_session=server_preserves_old_session,
        cursor_is_session_namespaced=cursor_is_session_namespaced,
        token_resource_matches_new_uri=token_resource_matches_new_uri,
    )

    if verdict == "transparent":
        return f"resume:{after.session_id}:{after.event_cursor}"

    if pending_tool_call is not None:
        # A boundary with an in-flight tool call is the dangerous case:
        # the call may have executed under the old session and its result
        # may be lost, or may have been silently downgraded under the new one.
        raise SessionMigrationBoundaryError(
            f"Cannot resume tool call {pending_tool_call!r} across session boundary "
            f"{before.fingerprint()} -> {after.fingerprint()}; "
            f"re-initialize and re-mint tokens against {after.endpoint_uri}"
        )

    return f"reinitialize:{after.session_id}"
