# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-resume-an-mcp-streamable-http-sse-session-because-its-resumption-token-has-silently-crossed-a-server-side-replay-horiz.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-resume-an-mcp-streamable-http-sse-session-because-its-resumption-token-has-silently-crossed-a-server-side-replay-horiz.warrant.json
# Markdown SHA-256:   f6b53af8eb17e13858594e51ca6344d069f5eb6f8cb6157886ba1131b68d9aa1
# Code AST SHA-256:   29b5d0a3409fbdc4fead4b974c5b44cf7fdc887d56e60e0d0309957416563e26
# Verified Classes:   ReplayHorizonCrossed, ResumedStream
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass
from typing import Optional


class ReplayHorizonCrossed(RuntimeError):
    """Raised when a resumed SSE stream skips events past Last-Event-ID."""


@dataclass
class ResumedStream:
    session_id: str
    last_event_id: int
    first_received_id: Optional[int]


_EVENT_ID_RE = re.compile(r"^id:\s*(\d+)\s*$")


def parse_first_event_id(raw_sse_head: str) -> Optional[int]:
    for line in raw_sse_head.splitlines():
        m = _EVENT_ID_RE.match(line.strip())
        if m:
            return int(m.group(1))
    return None


def validate_resume(stream: ResumedStream) -> None:
    """
    Enforce the replay-continuity invariant on a resumed stream.

    A resume is only a *continuation* if the first event ID equals
    last_event_id + 1. If it is strictly greater, the server's bounded
    event buffer discarded events in between and the stream must be
    treated as a re-sync, never as a continuation.
    """
    if stream.first_received_id is None:
        # No events yet; caller must not assume continuity. Defer.
        return

    expected = stream.last_event_id + 1
    got = stream.first_received_id

    if got == expected:
        return  # clean resume

    if got > expected:
        raise ReplayHorizonCrossed(
            f"session {stream.session_id}: resume skipped "
            f"{got - expected} event(s) "
            f"(last_event_id={stream.last_event_id}, "
            f"first_received_id={got}). "
            f"Treat pending awaits as indeterminate; "
            f"refresh tools/list and re-sync before continuing."
        )

    # got <= last_event_id: duplicate replay, handled by dedupe, not a gap.
    return


def resume_or_resync(session_id: str, last_event_id: int, sse_head: str) -> str:
    first = parse_first_event_id(sse_head)
    stream = ResumedStream(session_id, last_event_id, first)
    try:
        validate_resume(stream)
    except ReplayHorizonCrossed as exc:
        # Do NOT hand the stream to the runtime as a continuation.
        # Force full re-sync path.
        return f"RESYNC_REQUIRED: {exc}"
    return "CONTINUE"
