# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-resume-an-mcp-sse-session-after-migration-to-streamable-http-because-the-last-event-id-cursor-is-not-causally-anchored.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-resume-an-mcp-sse-session-after-migration-to-streamable-http-because-the-last-event-id-cursor-is-not-causally-anchored.warrant.json
# Markdown SHA-256:   15e6924e1948d14de88fb2392d748f0b9e8b14c5be311be9d6ec13ad57d8772b
# Code AST SHA-256:   8912fb0d87d177320c25a043e1c49031434c4fcd811f150de72d821649364ae3
# Verified Classes:   UnanchoredCursorError, Cursor
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass


class UnanchoredCursorError(RuntimeError):
    """Raised when a persisted Last-Event-ID cannot be proven to belong to
    the server's current event-ID namespace. Resuming would be a silent
    causal-reference failure (drop or foreign-replay)."""


@dataclass(frozen=True)
class Cursor:
    namespace: str
    seq: int

    def header(self) -> str:
        return f"{self.namespace}:{self.seq}"


_CURSOR_RE = re.compile(r"^(?P<ns>[A-Za-z0-9._-]+):(?P<seq>\d+)$")


def parse_cursor(raw: str) -> Cursor:
    m = _CURSOR_RE.match(raw)
    if not m:
        # Legacy bare integer from SSE era: namespace unknown.
        raise UnanchoredCursorError(
            f"cursor {raw!r} has no namespace tag; cannot anchor to Streamable HTTP event space"
        )
    return Cursor(namespace=m.group("ns"), seq=int(m.group("seq")))


def decide_resume(
    stored_raw: str,
    server_namespace: str,
    server_buffer_head: int | None,
) -> Cursor | None:
    """Return a cursor safe to send, or None to force checkpoint-based recovery."""
    try:
        cursor = parse_cursor(stored_raw)
    except UnanchoredCursorError:
        return None  # cannot verify; do not resume

    if cursor.namespace != server_namespace:
        # Different event space: replaying would be meaningless or foreign.
        return None

    if server_buffer_head is None:
        # Server has no replay buffer (e.g. post-redeploy). Namespace match
        # is necessary but not sufficient.
        return None

    if cursor.seq < server_buffer_head:
        # Cursor fell off the replay window; server would 410.
        return None

    return cursor


def resume_stream(stored_raw: str, server_namespace: str, server_buffer_head: int | None) -> str:
    cursor = decide_resume(stored_raw, server_namespace, server_buffer_head)
    if cursor is None:
        raise UnanchoredCursorError(
            f"refusing to resume with cursor {stored_raw!r} against namespace "
            f"{server_namespace!r} (buffer_head={server_buffer_head}); "
            "re-initialize and recover from durable checkpoint"
        )
    return cursor.header()
