# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-resume-an-mcp-streamable-session-across-an-sse-to-websocket-upgrade.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-resume-an-mcp-streamable-session-across-an-sse-to-websocket-upgrade.warrant.json
# Markdown SHA-256:   cb9488cf6a86d5d35146ae266c168139b8a54583882cbf80734992c832c99300
# Code AST SHA-256:   393a6f219b483f2435a801b16d9be96f0f28b029d5ee587afef2fbf94db2f3f9
# Verified Classes:   ResumptionRefused, SessionRecord, ResumeRequest
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from typing import Optional


class ResumptionRefused(RuntimeError):
    """Raised when an SSE->WebSocket resumption cursor cannot be proven continuous."""


@dataclass(frozen=True)
class SessionRecord:
    session_id: str
    epoch: str                 # issued at initialize, echoed by client on resume
    transport_generation: int  # incremented per accepted connection
    log_floor: int             # lowest event id still provable (pruning floor)
    log_head: int              # highest event id emitted


@dataclass(frozen=True)
class ResumeRequest:
    session_id: str
    epoch: str
    last_event_id: int
    upgrade_generation: int


def decide_resumption(record: Optional[SessionRecord], req: ResumeRequest) -> int:
    """
    Return the event id to replay from (exclusive), or raise ResumptionRefused.

    The invariant: a resume is valid only if the cursor N is inside the
    provably-continuous prefix [log_floor, log_head] of the *same* session
    incarnation (matching epoch and transport generation).
    """
    if record is None:
        raise ResumptionRefused(
            f"unknown session {req.session_id}; reinitialize required"
        )

    if record.session_id != req.session_id:
        raise ResumptionRefused(
            f"session id mismatch: record={record.session_id} req={req.session_id}"
        )

    # Epoch binds the session id to a single incarnation. A reaped-and-recreated
    # session with a reused id will have a different epoch.
    if record.epoch != req.epoch:
        raise ResumptionRefused(
            f"epoch mismatch for {req.session_id}: "
            f"record={record.epoch} req={req.epoch}; reinitialize required"
        )

    # Generation binds the cursor to the transport that issued it. An SSE cursor
    # cannot be replayed onto a WebSocket accepted under a different generation
    # unless the log is provably the same log.
    if record.transport_generation != req.upgrade_generation:
        raise ResumptionRefused(
            f"transport generation mismatch for {req.session_id}: "
            f"record={record.transport_generation} "
            f"upgrade={req.upgrade_generation}"
        )

    n = req.last_event_id

    if n < record.log_floor:
        raise ResumptionRefused(
            f"cursor {n} below pruned floor {record.log_floor} "
            f"for {req.session_id}; continuity unprovable"
        )

    if n > record.log_head:
        raise ResumptionRefused(
            f"cursor {n} exceeds log head {record.log_head} "
            f"for {req.session_id}; forged or corrupt cursor"
        )

    # n in [log_floor, log_head] under matching epoch+generation: replay n+1..head.
    return n
