# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-a-resumable-sse-resume-from-a-fresh-stream-when-the-mcp-http-transport-reuses-session-ids-across-reconnects.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-a-resumable-sse-resume-from-a-fresh-stream-when-the-mcp-http-transport-reuses-session-ids-across-reconnects.warrant.json
# Markdown SHA-256:   d7e007dadb9b16906f4f8b0a5cc15cd006dda2c45805920251c1aa7c377c8df2
# Code AST SHA-256:   c5e1b52aa376a09069ec8449f26ef6e5eba44785abd9b067ad1c7bccc4384990
# Verified Classes:   StreamResumeError, SessionStreamTracker
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class StreamResumeError(RuntimeError):
    """Raised when an SSE resume cannot be satisfied without a silent gap."""
    pass


class SessionStreamTracker:
    def __init__(self, buffer_ttl_s: int, session_ttl_s: int):
        if buffer_ttl_s < session_ttl_s:
            raise StreamResumeError(
                "buffer TTL must be >= session TTL; otherwise live sessions "
                "will produce 404s on resume and be mistaken for dead sessions"
            )
        self.buffer_ttl_s = buffer_ttl_s
        self.session_ttl_s = session_ttl_s
        self._had_stream: set[str] = set()
        self._last_event: dict[str, int] = {}

    def classify(self, session_id: str, last_event_id: int | None) -> str:
        prior = session_id in self._had_stream
        if last_event_id is None:
            if prior:
                # Cursor-less reconnect on a session that already streamed:
                # this is NOT a fresh stream. Treat as gapped resume.
                raise StreamResumeError(
                    f"session {session_id} reconnected without Last-Event-ID "
                    "after a prior stream; refusing to emit a silent gap"
                )
            return "fresh_initial"
        last = self._last_event.get(session_id)
        if last is None or last_event_id > last:
            raise StreamResumeError(
                f"cursor {last_event_id} ahead of server high-water mark "
                f"{last} for session {session_id}"
            )
        if last_event_id < last - self._retained_count(session_id):
            # Cursor older than retained buffer but session still live.
            raise StreamResumeError(
                f"cursor {last_event_id} beyond retention for live session "
                f"{session_id}; client must reconcile state, not re-init"
            )
        return "resume"

    def _retained_count(self, session_id: str) -> int:
        return max(0, int(self.buffer_ttl_s))
