# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-an-sse-to-streamable-http-resumption-has-silently-lost-event-continuity-in-mcp-transports.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-an-sse-to-streamable-http-resumption-has-silently-lost-event-continuity-in-mcp-transports.warrant.json
# Markdown SHA-256:   30bfd096e8e4998776b5bdfc3c4d8b3da37833daba66687f9fd0df602dd728f5
# Code AST SHA-256:   ac2dbffccbe2b6b6ec7b44989c0408aeea2d178e01e73230c6c243edb1163599
# Verified Classes:   ResumeContinuityError, ResumeToken
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hmac
import hashlib
from dataclasses import dataclass
from typing import Optional


class ResumeContinuityError(RuntimeError):
    """Raised when a streamable-HTTP resumption cannot prove cursor continuity."""


@dataclass(frozen=True)
class ResumeToken:
    session_id: str
    channel_id: str
    monotonic_seq: int
    signature: str


def issue_resume_token(secret: bytes, session_id: str, channel_id: str, seq: int) -> ResumeToken:
    payload = f"{session_id}|{channel_id}|{seq}".encode()
    sig = hmac.new(secret, payload, hashlib.sha256).hexdigest()
    return ResumeToken(session_id, channel_id, seq, sig)


def verify_resumption(
    secret: bytes,
    token: ResumeToken,
    attaching_channel_id: str,
    expected_next_seq: int,
    server_high_water: int,
) -> int:
    payload = f"{token.session_id}|{token.channel_id}|{token.monotonic_seq}".encode()
    expected_sig = hmac.new(secret, payload, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected_sig, token.signature):
        raise ResumeContinuityError(
            f"resume token signature invalid for session {token.session_id}"
        )
    if token.channel_id != attaching_channel_id:
        raise ResumeContinuityError(
            f"channel mismatch: token issued for {token.channel_id!r}, "
            f"client attaching to {attaching_channel_id!r}; "
            f"event IDs are per-channel and cannot be replayed across channels"
        )
    if token.monotonic_seq + 1 != expected_next_seq:
        raise ResumeContinuityError(
            f"client expected next seq {expected_next_seq}, "
            f"token carries {token.monotonic_seq}; client state is stale"
        )
    if token.monotonic_seq >= server_high_water:
        raise ResumeContinuityError(
            f"token seq {token.monotonic_seq} >= server high-water {server_high_water}; "
            f"server has no replayable events beyond this point"
        )
    return token.monotonic_seq + 1


def resume_stream(
    secret: bytes,
    token: ResumeToken,
    attaching_channel_id: str,
    expected_next_seq: int,
    server_high_water: int,
) -> int:
    try:
        return verify_resumption(
            secret, token, attaching_channel_id, expected_next_seq, server_high_water
        )
    except ResumeContinuityError:
        # Force caller into reconciliation: do not mark session RESUMED.
        raise
