# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-resume-an-mcp-stream-the-last-event-id-replay-divergence-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-resume-an-mcp-stream-the-last-event-id-replay-divergence-boundary.warrant.json
# Markdown SHA-256:   9e6ff54e9e3c9255588f846e02f0ada3784f18cd29f549d30eb43fdc4307d98c
# Code AST SHA-256:   c0e3b014c501422ede55c02910257c255d0f952c1c33e5cb469ffc82ef78e98e
# Verified Classes:   StreamResumptionDivergence, Event, ResumeRequest
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StreamResumptionDivergence(RuntimeError):
    """Raised when a Last-Event-ID cannot be proven contiguous with the retained log."""


@dataclass(frozen=True)
class Event:
    generation: str
    seq: int
    payload: dict

    @property
    def token(self) -> str:
        return f"{self.generation}.{self.seq}"


@dataclass(frozen=True)
class ResumeRequest:
    session_id: str
    last_event_id: Optional[str]  # None on first connect


def parse_token(token: str) -> tuple[str, int]:
    gen, _, seq = token.partition(".")
    if not gen or not seq.isdigit():
        raise StreamResumptionDivergence(f"malformed Last-Event-ID: {token!r}")
    return gen, int(seq)


def resume_stream(
    req: ResumeRequest,
    buffer: list[Event],
    current_generation: str,
) -> list[Event]:
    """Return events to replay, or raise if continuity cannot be proven.

    Invariant: an empty return is only legal when the client is provably
    caught up to the head of the *same* generation.
    """
    if not buffer:
        # No retained events. If the client claims a position, we cannot
        # prove it exists. Refuse rather than replay nothing.
        if req.last_event_id is not None:
            raise StreamResumptionDivergence(
                f"session {req.session_id}: empty buffer, cannot honor "
                f"Last-Event-ID={req.last_event_id!r}"
            )
        return []

    if req.last_event_id is None:
        # Fresh connect: replay the whole retained buffer.
        return list(buffer)

    last_gen, last_seq = parse_token(req.last_event_id)

    if last_gen != current_generation:
        raise StreamResumptionDivergence(
            f"session {req.session_id}: Last-Event-ID generation {last_gen!r} "
            f"!= current generation {current_generation!r}; stream is lost, "
            f"not resumable"
        )

    min_seq = min(e.seq for e in buffer if e.generation == current_generation)

    # The boundary: a gap between the client's position and the oldest
    # retained event means events were dropped. Replay would be incomplete.
    if last_seq + 1 < min_seq:
        raise StreamResumptionDivergence(
            f"session {req.session_id}: gap between Last-Event-ID seq "
            f"{last_seq} and oldest retained seq {min_seq}; "
            f"{min_seq - last_seq - 1} event(s) unrecoverable"
        )

    replay = [e for e in buffer if e.generation == current_generation and e.seq > last_seq]

    # Contiguity assertion: the replay must be exactly the run the client
    # is missing, with no holes.
    expected = list(range(last_seq + 1, last_seq + 1 + len(replay)))
    actual = [e.seq for e in replay]
    if actual != expected:
        raise StreamResumptionDivergence(
            f"session {req.session_id}: non-contiguous replay "
            f"expected {expected}, got {actual}"
        )

    return replay
