# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-sse-stream-resumption-as-a-fresh-subscription-rather-than-a-continuation.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-sse-stream-resumption-as-a-fresh-subscription-rather-than-a-continuation.warrant.json
# Markdown SHA-256:   764cbdfb71dbee4d6d0a2fc531321f7354db2575b62af186b54643f009e95252
# Code AST SHA-256:   050468b4d3245cfff120da012dc8c0721fc5a099ce9650d8fb1ecf76d3d88ce1
# Verified Classes:   ResumeContinuityError, EventStore
# Defensive Guards:   8 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class ResumeContinuityError(RuntimeError):
    """Raised when a Last-Event-ID resume cannot be proven continuous."""

    def __init__(self, reason: str, requested_id: int, detail: str):
        super().__init__(f"{reason}: requested={requested_id} ({detail})")
        self.reason = reason
        self.requested_id = requested_id
        self.detail = detail


@dataclass
class EventStore:
    head: int                 # highest event ID ever written
    floor: int                # lowest event ID still retained (ring buffer)
    session_id: str
    tenant: str
    subscription_live: bool
    terminal_emitted: bool
    contiguous_ids: bool = True


def resume_stream(
    store: EventStore,
    requested_id: int,
    request_session_id: str,
    request_tenant: str,
    replay_window_seconds: float,
    idle_seconds: float,
) -> list[int]:
    """Return the event IDs to replay, or raise ResumeContinuityError.

    The caller MUST treat any raise as 'fresh subscription', not 'retry'.
    """
    # 1. Authority: cursor is a capability bound to session + tenant.
    if store.session_id != request_session_id:
        raise ResumeContinuityError(
            "cursor_scope_mismatch", requested_id,
            f"cursor session {store.session_id!r} != request {request_session_id!r}",
        )
    if store.tenant != request_tenant:
        raise ResumeContinuityError(
            "cursor_scope_mismatch", requested_id,
            f"cursor tenant {store.tenant!r} != request {request_tenant!r}",
        )

    # 2. Liveness: a terminal subscription whose terminal event has been
    #    evicted is dangling; do not hold the connection open.
    if not store.subscription_live:
        if store.terminal_emitted and requested_id < store.floor:
            raise ResumeContinuityError(
                "dangling_terminal_cursor", requested_id,
                f"terminal evicted below floor {store.floor}",
            )
        if not store.terminal_emitted:
            raise ResumeContinuityError(
                "subscription_reaped", requested_id,
                "producer gone without terminal event",
            )

    # 3. Continuity: requested ID must be within the retained range.
    if requested_id < store.floor:
        raise ResumeContinuityError(
            "replay_window_exceeded", requested_id,
            f"floor={store.floor} head={store.head}",
        )
    if requested_id > store.head:
        raise ResumeContinuityError(
            "cursor_ahead_of_head", requested_id,
            f"head={store.head}",
        )

    # 4. Monotonicity: if IDs are not contiguous, the caller must emit an
    #    explicit gap frame; we cannot prove absence of loss here.
    if not store.contiguous_ids:
        raise ResumeContinuityError(
            "non_contiguous_id_contract", requested_id,
            "server must emit explicit resume-gap frame",
        )

    # 5. Idle bound: a subscription idle beyond the replay window is treated
    #    as fresh even if the cursor is technically retained.
    if idle_seconds > replay_window_seconds:
        raise ResumeContinuityError(
            "idle_exceeded_replay_window", requested_id,
            f"idle={idle_seconds:.1f}s window={replay_window_seconds:.1f}s",
        )

    return list(range(requested_id + 1, store.head + 1))
