# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-sse-event-id-reuse-from-corrupting-resumed-mcp-sessions-after-a-transport-level-reconnect.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-sse-event-id-reuse-from-corrupting-resumed-mcp-sessions-after-a-transport-level-reconnect.warrant.json
# Markdown SHA-256:   c3c23989bd1b78db8a62f784352154186fb636074befcb1bb240cd3f73b284e0
# Code AST SHA-256:   4fec68fa469eaa0d1e8ab3f8da2849cda43bf34bf3aa20c654d7588d539bb874
# Verified Classes:   SessionResumeViolation, EventToken, ResumeGate
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass
from typing import Optional


class SessionResumeViolation(RuntimeError):
    """Raised when an SSE Last-Event-ID resume cannot be proven to belong
    to the current logical session epoch."""
    pass


@dataclass(frozen=True)
class EventToken:
    session_id: str
    epoch: int
    seq: int

    def encode(self) -> str:
        raw = f"{self.session_id}:{self.epoch}:{self.seq}".encode()
        return f"{self.epoch}.{self.seq}.{hashlib.sha256(raw).hexdigest()[:16]}"

    @classmethod
    def decode(cls, token: str) -> "EventToken":
        try:
            epoch_s, seq_s, digest = token.split(".", 2)
            return cls(session_id="", epoch=int(epoch_s), seq=int(seq_s))
        except (ValueError, AttributeError) as exc:
            raise SessionResumeViolation(f"malformed Last-Event-ID: {token!r}") from exc


class ResumeGate:
    """Validates that a reconnect resumes the SAME session epoch with no gap."""

    def __init__(self, session_id: str, epoch: int, retained_floor_seq: int,
                 head_seq: int):
        self.session_id = session_id
        self.epoch = epoch
        self.retained_floor_seq = retained_floor_seq
        self.head_seq = head_seq

    def validate_resume(self, last_event_id: Optional[str]) -> EventToken:
        if last_event_id is None:
            # Fresh connection, no resume claimed: start at head.
            return EventToken(self.session_id, self.epoch, self.head_seq)

        tok = EventToken.decode(last_event_id)

        if tok.epoch != self.epoch:
            # Counter restart or stale session: cannot resume, must resync.
            raise SessionResumeViolation(
                f"epoch mismatch: client at epoch {tok.epoch}, "
                f"server at epoch {self.epoch}; full session resync required"
            )

        if tok.seq < self.retained_floor_seq:
            # Requested event already evicted from the ring buffer.
            raise SessionResumeViolation(
                f"event seq {tok.seq} evicted (floor={self.retained_floor_seq}); "
                f"cannot guarantee gap-free replay"
            )

        if tok.seq > self.head_seq:
            # Client claims to have seen events the server never emitted.
            raise SessionResumeViolation(
                f"event seq {tok.seq} exceeds head {self.head_seq}; "
                f"possible cross-session token injection"
            )

        return EventToken(self.session_id, self.epoch, tok.seq)


def handle_reconnect(gate: ResumeGate, last_event_id: Optional[str]) -> int:
    try:
        resume_point = gate.validate_resume(last_event_id)
    except SessionResumeViolation:
        # Fail closed: emit explicit resync signal, never resume-at-head.
        raise
    return resume_point.seq


if __name__ == "__main__":
    gate = ResumeGate(session_id="s-42", epoch=7, retained_floor_seq=1000,
                      head_seq=5000)
    # Valid resume:
    assert handle_reconnect(gate, "7.4999.deadbeefdeadbeef") == 4999
    # Evicted event -> must raise, not silently resume at head:
    try:
        handle_reconnect(gate, "7.10.deadbeefdeadbeef")
    except SessionResumeViolation as e:
        print("correctly rejected:", e)
    # Stale epoch from pre-restart client:
    try:
        handle_reconnect(gate, "3.4999.deadbeefdeadbeef")
    except SessionResumeViolation as e:
        print("correctly rejected:", e)
