# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-resume-an-sse-stream-after-migrating-to-streamable-http-the-last-event-id-replay-window-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-resume-an-sse-stream-after-migrating-to-streamable-http-the-last-event-id-replay-window-invariant.warrant.json
# Markdown SHA-256:   14d4643213954d9880181a930a143ce0b363785e0b197207c8d6c4ff2f9caab0
# Code AST SHA-256:   9beb89b3b1c021f7f3f501f8bb8ba720ae83df3e2143e4598ac9aeb4f9b36e0e
# Verified Classes:   ResumabilityLost, EventLog
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class ResumabilityLost(RuntimeError):
    """Raised when a Last-Event-ID cannot be honored in the target session."""


@dataclass(frozen=True)
class EventLog:
    session_id: str
    oldest_retained: int
    high_water_mark: int  # last event ID ever minted in this session

    def can_resume(self, cursor: int) -> bool:
        return self.oldest_retained <= cursor <= self.high_water_mark


def resume_stream(
    log: EventLog,
    cursor: int,
    cursor_session_id: str,
) -> list[int]:
    """
    Validate a resume request against the target session's event log.

    Invariant: a cursor is only resumable within the session that minted it,
    AND only if it lies within [oldest_retained, high_water_mark]. A cursor
    ahead of the high-water mark means the client is migrating from a
    different (or torn-down) session and the intervening events are gone.
    """
    if cursor_session_id != log.session_id:
        raise ResumabilityLost(
            f"cursor minted by session {cursor_session_id!r} cannot resume "
            f"session {log.session_id!r}"
        )
    if cursor > log.high_water_mark:
        raise ResumabilityLost(
            f"cursor {cursor} exceeds high-water mark {log.high_water_mark}; "
            f"events in ({log.high_water_mark}, {cursor}] are unavailable"
        )
    if cursor < log.oldest_retained:
        raise ResumabilityLost(
            f"cursor {cursor} predates oldest retained event "
            f"{log.oldest_retained}; replay window evicted"
        )
    return list(range(cursor + 1, log.high_water_mark + 1))


def migrate_and_resume(
    new_session: EventLog,
    last_event_id: str,
    last_event_session: str,
) -> list[int]:
    """
    Client-side entry point for SSE -> Streamable HTTP migration.
    Parses the cursor and enforces the invariant. Empty replay is NOT
    treated as success — the caller must reconcile against a checkpoint.
    """
    prefix = "sse-"
    if not last_event_id.startswith(prefix):
        raise ResumabilityLost(f"unparseable Last-Event-ID: {last_event_id!r}")
    cursor = int(last_event_id[len(prefix):])

    replayed = resume_stream(new_session, cursor, last_event_session)
    if not replayed:
        # No events between cursor and head. This is the ambiguous case:
        # we cannot distinguish "nothing happened" from "we lost the gap".
        # Force checkpoint reconciliation rather than silently continuing.
        raise ResumabilityLost(
            f"empty replay after migration (cursor={cursor}); "
            f"reconcile agent state from checkpoint before continuing"
        )
    return replayed
