# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-sse-event-id-monotonicity-against-the-mcp-last-event-id-replay-window-when-an-http-native-stream-resumes-mid-tool-cal.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-sse-event-id-monotonicity-against-the-mcp-last-event-id-replay-window-when-an-http-native-stream-resumes-mid-tool-cal.warrant.json
# Markdown SHA-256:   098e257bcd53ab6a8d2700f96562000b29558be4a29666645f85131d8d4a12ba
# Code AST SHA-256:   8de7c5ca12720744444f0d5f298bfc18c5bd41b2268c942edc5168eb1574adcb
# Verified Classes:   StreamCursorDesync, ResumeState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class StreamCursorDesync(RuntimeError):
    """Raised when a resumed MCP SSE stream cannot be reconciled to the durable cursor."""
    pass


@dataclass
class ResumeState:
    session_id: str
    durable_cursor: int          # last event ID whose side effect is committed
    idempotency_key: str         # per-tool-call, survives reconnect


def reconcile_resume(
    state: ResumeState,
    first_replayed_id: Optional[int],
    server_window_floor: int,
    server_window_ceiling: int,
) -> str:
    """
    Decide how to handle the first event after a stream resume.
    Returns one of: 'process', 'reconcile_snapshot', 'replay_from_cursor'.
    Raises StreamCursorDesync when the server's window cannot satisfy the cursor.
    """
    if first_replayed_id is None:
        # Server sent no replay event. Could mean "nothing pending" OR "log lost".
        if state.durable_cursor < server_window_ceiling:
            raise StreamCursorDesync(
                f"session {state.session_id}: server reports ceiling "
                f"{server_window_ceiling} but replayed nothing for cursor "
                f"{state.durable_cursor}; cannot distinguish empty tail from lost log"
            )
        return "process"

    if first_replayed_id == state.durable_cursor:
        # Duplicate of an already-committed event. Safe to re-ack, must not re-execute.
        return "process"

    if first_replayed_id == state.durable_cursor + 1:
        return "process"

    if first_replayed_id > state.durable_cursor + 1:
        # Gap: events were lost between cursor and replay start.
        return "replay_from_cursor"

    # first_replayed_id < durable_cursor: server rewound below our committed point.
    # This is the per-connection-counter failure. Refuse to proceed silently.
    if state.durable_cursor > server_window_ceiling:
        raise StreamCursorDesync(
            f"session {state.session_id}: cursor {state.durable_cursor} exceeds "
            f"server ceiling {server_window_ceiling}; session log was reset or "
            f"evicted, resumption is unsound"
        )
    return "reconcile_snapshot"


def commit_event(state: ResumeState, event_id: int, payload: bytes) -> ResumeState:
    """Advance the durable cursor only after the side effect is persisted."""
    if event_id != state.durable_cursor + 1 and event_id != state.durable_cursor:
        raise StreamCursorDesync(
            f"session {state.session_id}: cannot commit event {event_id} "
            f"out of order against cursor {state.durable_cursor}"
        )
    new_key = hashlib.sha256(payload + str(event_id).encode()).hexdigest()[:16]
    return ResumeState(
        session_id=state.session_id,
        durable_cursor=max(state.durable_cursor, event_id),
        idempotency_key=new_key,
    )
