# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abandon-an-sse-event-id-after-an-mcp-session-migration.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abandon-an-sse-event-id-after-an-mcp-session-migration.warrant.json
# Markdown SHA-256:   6b4e269c7b9ea1d18e1a87ab1b5b5efc0f9b2f72a6d165c059c8012f02dca0f5
# Code AST SHA-256:   60360657ebc177a11034f0674d1ffe39e0ae3aa20a0b0657fd4ff3d13402950a
# Verified Classes:   EventSpaceContinuityError, EventId
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from __future__ import annotations

import re
from dataclasses import dataclass


class EventSpaceContinuityError(RuntimeError):
    """Raised when a resume request cannot be proven to belong to the
    current producer's event-ID space. Never swallow this into a
    numeric-comparison fallback."""


_EPOCH_SEQ = re.compile(r"^(?P<epoch>[0-9a-f]{8,}):(?P<seq>\d+)$")


@dataclass(frozen=True)
class EventId:
    epoch: str
    seq: int

    @classmethod
    def parse(cls, raw: str) -> "EventId":
        m = _EPOCH_SEQ.match(raw)
        if not m:
            raise EventSpaceContinuityError(
                f"unparseable Last-Event-ID {raw!r}: no epoch fence present"
            )
        return cls(epoch=m.group("epoch"), seq=int(m.group("seq")))

    def render(self) -> str:
        return f"{self.epoch}:{self.seq}"


def decide_resume(
    *,
    session_id: str,
    last_event_id_raw: str | None,
    current_producer_epoch: str,
    buffer_min_seq: int | None,
    buffer_max_seq: int | None,
) -> int | None:
    """Return the sequence number to resume *after*, or None to start fresh.

    Raises EventSpaceContinuityError when the request must be rejected with a
    typed resume failure instead of a silent continuation.
    """
    if last_event_id_raw is None:
        return None

    try:
        presented = EventId.parse(last_event_id_raw)
    except EventSpaceContinuityError:
        # Unverifiable is not valid. Reject; do not clamp.
        raise EventSpaceContinuityError(
            f"session {session_id}: Last-Event-ID {last_event_id_raw!r} "
            "carries no producer epoch; refusing to resume across an "
            "unverifiable event space"
        )

    if presented.epoch != current_producer_epoch:
        # Migration or restart changed the producer. Session ID continuity
        # does NOT imply event-ID continuity. Reject with the new epoch so
        # the client can resume from a logical checkpoint.
        raise EventSpaceContinuityError(
            f"session {session_id}: Last-Event-ID epoch {presented.epoch!r} "
            f"does not match current producer epoch "
            f"{current_producer_epoch!r}; resume rejected, client must "
            f"re-establish from logical checkpoint"
        )

    if buffer_min_seq is None or buffer_max_seq is None:
        raise EventSpaceContinuityError(
            f"session {session_id}: epoch matched but no event buffer is "
            "attached to this producer; cannot prove replay range"
        )

    if presented.seq < buffer_min_seq - 1:
        # Buffer trimmed past the requested position: a real gap exists.
        raise EventSpaceContinuityError(
            f"session {session_id}: requested resume after seq "
            f"{presented.seq} but buffer starts at {buffer_min_seq}; "
            f"gap of {buffer_min_seq - presented.seq - 1} events"
        )

    if presented.seq > buffer_max_seq:
        raise EventSpaceContinuityError(
            f"session {session_id}: Last-Event-ID seq {presented.seq} is "
            f"ahead of producer max {buffer_max_seq}; client and server "
            "disagree on stream position"
        )

    return presented.seq
