# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-a-resumed-sse-stream-from-a-replayed-one-under-mcp-streamable-http-transport.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-a-resumed-sse-stream-from-a-replayed-one-under-mcp-streamable-http-transport.warrant.json
# Markdown SHA-256:   c6a764255ee3e9eb74677350d3726f127df824fb60196a81b5a11af4706608c1
# Code AST SHA-256:   e743341399b13013743c27fba7c7f0629583c4b1190e9a0a09afd2e1790f5936
# Verified Classes:   StreamResumptionError, Event
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass


class StreamResumptionError(RuntimeError):
    """Raised when a reconnected SSE stream cannot be proven to be a true
    resumption past the client's durable cursor (replay, gap, or reset)."""


@dataclass(frozen=True)
class Event:
    seq: int | None          # parsed from SSE `id`; None if opaque/absent
    epoch: int               # session epoch; bumped on server buffer reinit
    is_reset_marker: bool = False


def classify_reconnect(
    cursor_seq: int,
    cursor_epoch: int,
    first_event: Event,
) -> str:
    """Return 'resume' only when monotonic advance past the durable cursor is
    proven. Otherwise return 'reconcile' (replay, gap, or reset)."""
    if first_event.is_reset_marker:
        return "reconcile"
    if first_event.seq is None:
        # Opaque id: cannot prove advance -> unsafe to apply deltas.
        return "reconcile"
    if first_event.epoch != cursor_epoch:
        # Server reset its buffer; sequence space restarted.
        return "reconcile"
    if first_event.seq <= cursor_seq:
        # Replay or regression of the same sequence space.
        return "reconcile"
    return "resume"


def apply_resumed_stream(
    cursor_seq: int,
    cursor_epoch: int,
    events: list[Event],
    apply_delta,
    reconcile_state,
) -> int:
    if not events:
        raise StreamResumptionError("empty stream on reconnect: cannot classify")
    verdict = classify_reconnect(cursor_seq, cursor_epoch, events[0])
    if verdict != "resume":
        # Do not apply deltas; fetch authoritative state first.
        reconcile_state()
        return events[-1].seq if events[-1].seq is not None else cursor_seq
    new_cursor = cursor_seq
    for ev in events:
        if ev.seq is None or ev.seq <= new_cursor:
            raise StreamResumptionError(
                f"non-monotonic event seq={ev.seq} after cursor={new_cursor}"
            )
        apply_delta(ev)
        new_cursor = ev.seq  # write-ahead: persist before next apply
    return new_cursor
