# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-mcp-resumable-sse-stream-has-silently-forked-past-its-last-event-id-watermark.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-mcp-resumable-sse-stream-has-silently-forked-past-its-last-event-id-watermark.warrant.json
# Markdown SHA-256:   932cffb23f46f3b6861fa81a167cf8ee79bb37be64b9475e8052fc5466d7e20d
# Code AST SHA-256:   cf29d86959f57d7fc9c20049f419b273f9e510ac4672daf889468ccd6cd90ec9
# Verified Classes:   ResumptionForkError, SessionToken
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import hmac
import json
from dataclasses import dataclass


class ResumptionForkError(RuntimeError):
    """Raised when an SSE resumption cannot be proven contiguous with the client's cursor."""
    pass


@dataclass(frozen=True)
class SessionToken:
    session_id: str
    last_event_id: int
    signature: str


def issue_token(secret: bytes, session_id: str, last_event_id: int) -> SessionToken:
    payload = f"{session_id}:{last_event_id}".encode()
    sig = hmac.new(secret, payload, hashlib.sha256).hexdigest()
    return SessionToken(session_id, last_event_id, sig)


def verify_resumption(
    secret: bytes,
    token: SessionToken,
    client_last_event_id: int,
    authoritative_head: int,
    oldest_retained_id: int,
) -> int:
    """Return the next event id to emit, or raise if the resumption would fork the stream."""
    expected_sig = hmac.new(
        secret, f"{token.session_id}:{token.last_event_id}".encode(), hashlib.sha256
    ).hexdigest()
    if not hmac.compare_digest(expected_sig, token.signature):
        raise ResumptionForkError(
            f"session token signature invalid for session={token.session_id}"
        )

    if token.last_event_id != client_last_event_id:
        raise ResumptionForkError(
            f"cursor mismatch: token says {token.last_event_id}, "
            f"client says {client_last_event_id} — refusing to fork"
        )

    if client_last_event_id > authoritative_head:
        raise ResumptionForkError(
            f"client cursor {client_last_event_id} ahead of server head "
            f"{authoritative_head} — client is on a divergent history"
        )

    if client_last_event_id < oldest_retained_id - 1:
        raise ResumptionForkError(
            f"cursor {client_last_event_id} evicted (oldest retained "
            f"{oldest_retained_id}) — must reconcile, not replay"
        )

    return client_last_event_id + 1


def on_reconnect(
    secret: bytes,
    token: SessionToken,
    client_last_event_id: int,
    authoritative_head: int,
    oldest_retained_id: int,
) -> dict:
    try:
        next_id = verify_resumption(
            secret, token, client_last_event_id, authoritative_head, oldest_retained_id
        )
    except ResumptionForkError as exc:
        # Force reconciliation: snapshot + explicit gap marker, no synthesized replay.
        return {
            "event": "replay_gap",
            "data": json.dumps(
                {
                    "reason": str(exc),
                    "requested": client_last_event_id,
                    "head": authoritative_head,
                    "require_reconcile": True,
                }
            ),
        }
    return {"event": "resume", "next_event_id": next_id}
