# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-torn-sse-event-stream-boundary-during-mcp-http-native-transport-session-resumption.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-torn-sse-event-stream-boundary-during-mcp-http-native-transport-session-resumption.warrant.json
# Markdown SHA-256:   a68d1fc281104cdae98fe1e278ba7fa566a30dd68e940823fa232020508215c8
# Code AST SHA-256:   64db3f1c91c148f0690beb3a3626f178f1ecbeb845c4759795a84a7455df767b
# Verified Classes:   TornStreamResumeError, SseResumeState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import json
from dataclasses import dataclass, field


class TornStreamResumeError(RuntimeError):
    """Raised when a resume would fuse a pre-drop partial event with replayed bytes."""


@dataclass
class SseResumeState:
    last_dispatched_id: int = 0
    generation: int = 0
    partial_tail: bytes = field(default=b"")


def begin_resume(state: SseResumeState, first_replayed_id: int) -> int:
    """
    Prepare a resume. Enforces two invariants:
      1. The partial tail from before the drop is discarded, never merged.
      2. The resume cursor is the last *dispatched* event id, and the first
         replayed id must be exactly last_dispatched_id + 1 (no silent gap).
    Returns the id to send in Last-Event-ID.
    """
    if state.partial_tail:
        # Bytes after the last terminator belong to an event we never fully
        # received. Merging them with replay fuses two events and forward-labels
        # the corruption with the replayed event's id.
        state.partial_tail = b""

    state.generation += 1

    expected_next = state.last_dispatched_id + 1
    if first_replayed_id != expected_next:
        raise TornStreamResumeError(
            f"resume gap: last dispatched id={state.last_dispatched_id}, "
            f"expected replay to start at {expected_next}, got {first_replayed_id}; "
            f"refusing to resume with a hole in the event stream"
        )

    return state.last_dispatched_id


def dispatch_event(state: SseResumeState, raw_event: bytes) -> dict:
    """
    Dispatch a fully-terminated SSE event. The cursor advances only here,
    never on id-line parse.
    """
    if not raw_event.endswith(b"\n\n"):
        raise TornStreamResumeError(
            "dispatch called on un-terminated event; parser must emit only on \\n\\n"
        )
    event_id = None
    data_lines = []
    for line in raw_event.decode("utf-8").splitlines():
        if line.startswith("id:"):
            event_id = int(line[3:].strip())
        elif line.startswith("data:"):
            data_lines.append(line[5:].lstrip())
    payload = json.loads("\n".join(data_lines))
    if event_id is not None:
        if event_id <= state.last_dispatched_id:
            raise TornStreamResumeError(
                f"non-monotonic event id {event_id} after {state.last_dispatched_id}"
            )
        state.last_dispatched_id = event_id
    return payload
