# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-mcp-sse-resumption-as-invalid-across-a-re-established-chunked-stream.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-mcp-sse-resumption-as-invalid-across-a-re-established-chunked-stream.warrant.json
# Markdown SHA-256:   568ab20c7ec02dea50212ca4fa8cd6d044f8bb3cd40dd1fcd4998fb647b5f225
# Code AST SHA-256:   9b653880dddd7a10a9be9bce9ec21a0a1100edfdac7fb4042df0635fdfb25404
# Verified Classes:   ResumeEpochInvalid, StreamState, ResumeContext
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class ResumeEpochInvalid(RuntimeError):
    """Raised when an SSE resume token cannot be proven to belong to the
    current multiplexing epoch, so resumption would silently lose events."""
    pass


@dataclass
class StreamState:
    stream_id: str
    last_seq: int
    terminal_outstanding: bool = False


@dataclass
class ResumeContext:
    session_id: str
    last_event_id: Optional[int]
    per_session_replay_advertised: bool
    multiplexed_streams: list[StreamState] = field(default_factory=list)
    counter_epoch: Optional[str] = None  # server-asserted epoch tag, if any


def validate_resume(ctx: ResumeContext, first_event_id: int,
                    first_event_epoch: Optional[str]) -> None:
    # Guardrail 1: bare integer token over multiple streams is unverifiable.
    if ctx.last_event_id is not None and len(ctx.multiplexed_streams) > 1 \
            and not ctx.per_session_replay_advertised:
        raise ResumeEpochInvalid(
            f"session {ctx.session_id}: bare Last-Event-ID {ctx.last_event_id} "
            f"over {len(ctx.multiplexed_streams)} multiplexed streams without "
            f"per-session replay capability; resume unverifiable"
        )

    # Guardrail 2: ID must be strictly greater AND in the same epoch.
    if ctx.last_event_id is not None and first_event_id <= ctx.last_event_id:
        raise ResumeEpochInvalid(
            f"session {ctx.session_id}: counter rotated on reconnect "
            f"(resume {ctx.last_event_id}, first new {first_event_id})"
        )
    if ctx.counter_epoch is not None and first_event_epoch is not None \
            and first_event_epoch != ctx.counter_epoch:
        raise ResumeEpochInvalid(
            f"session {ctx.session_id}: epoch changed "
            f"({ctx.counter_epoch} -> {first_event_epoch}); "
            f"ID space reused, replay untrustworthy"
        )

    # Guardrail 3: any outstanding terminal event cannot be recovered
    # by a resume the client cannot verify.
    pending = [s.stream_id for s in ctx.multiplexed_streams
               if s.terminal_outstanding]
    if pending:
        raise ResumeEpochInvalid(
            f"session {ctx.session_id}: terminal events outstanding on "
            f"streams {pending}; must re-issue with idempotency keys, "
            f"not resume"
        )


def on_sse_reconnect(ctx: ResumeContext, first_event_id: int,
                     first_event_epoch: Optional[str]) -> str:
    try:
        validate_resume(ctx, first_event_id, first_event_epoch)
    except ResumeEpochInvalid:
        # Fail closed: re-establish session, re-issue outstanding requests.
        return "reestablish_session"
    return "resume"
