# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-last-event-id-resume-as-a-new-session-rather-than-a-continuation-and-why-silent-acceptance-corrupt.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-last-event-id-resume-as-a-new-session-rather-than-a-continuation-and-why-silent-acceptance-corrupt.warrant.json
# Markdown SHA-256:   e7cad2ac9ddd3ffa56afb450505c42b94504b8030bf788182d13e484f16d8324
# Code AST SHA-256:   af73f5008ba03acde79189908d2175c5215a0ff199dddfdf47590d5499438529
# Verified Classes:   ResumeIncoherenceError, SessionState
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ResumeIncoherenceError(RuntimeError):
    """Raised when a resumable MCP GET cannot honor Last-Event-ID contiguity."""


@dataclass
class SessionState:
    session_id: str
    oldest_retained_event: int
    newest_emitted_event: int
    # event IDs currently retained; must be a contiguous suffix to be resumable
    retained_event_ids: set[int] = field(default_factory=set)
    # in-flight request correlation table; replay is incoherent without it
    inflight_request_ids: set[str] = field(default_factory=set)


def can_faithfully_resume(session: SessionState, last_event_id: int) -> bool:
    if last_event_id < session.oldest_retained_event:
        return False
    if last_event_id > session.newest_emitted_event:
        return False
    # contiguity: every id in (last_event_id, newest] must be retained
    for eid in range(last_event_id + 1, session.newest_emitted_event + 1):
        if eid not in session.retained_event_ids:
            return False
    return True


def handle_resumable_get(
    session: Optional[SessionState],
    last_event_id: Optional[int],
) -> int:
    if session is None:
        return 404  # client must initialize a new session
    if last_event_id is None:
        return 200  # live subscribe from tail, no replay promised
    if not can_faithfully_resume(session, last_event_id):
        # MUST NOT return 200: silent acceptance corrupts agent tool state
        raise ResumeIncoherenceError(
            f"session {session.session_id}: cannot resume from "
            f"Last-Event-ID={last_event_id} (retained "
            f"[{session.oldest_retained_event},{session.newest_emitted_event}], "
            f"gaps present or dependency state missing)"
        )
    return 200  # contiguous replay from last_event_id+1 then live tail
