# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-sse-resumption-after-mcp-session-rehydration-and-why-the-last-event-id-alone-cannot-bound-replay-diverge.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-sse-resumption-after-mcp-session-rehydration-and-why-the-last-event-id-alone-cannot-bound-replay-diverge.warrant.json
# Markdown SHA-256:   91ae40105a3912f2b3e924dd8b7d7266f73b88540cbf3b5bdf1d5b9aba006b7c
# Code AST SHA-256:   5e783ff26dd1b2da8bd69e350fe9bc0afa7fa31e8ee677beb7a92a087821147c
# Verified Classes:   ResumptionEpochViolation, StreamCursor
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ResumptionEpochViolation(RuntimeError):
    """Raised when a client attempts SSE replay-dedup across an unprovable epoch boundary."""


@dataclass
class StreamCursor:
    session_id: str
    epoch: str               # server-issued generation token, changes on rehydration
    last_event_id: int = 0
    idempotency_key: Optional[str] = None


def reconcile_reconnect(
    cursor: StreamCursor,
    server_session_id: str,
    server_epoch: Optional[str],
    first_event_id: int,
) -> str:
    """
    Decide resume / rebase / restart on SSE reconnect.
    Returns the action; raises if the client cannot safely decide.
    """
    if server_session_id != cursor.session_id:
        # Session was evicted and recreated: never resume, restart with idempotency key.
        if cursor.idempotency_key is None:
            raise ResumptionEpochViolation(
                f"session {cursor.session_id!r} replaced by {server_session_id!r} "
                "with no idempotency key; cannot restart safely"
            )
        return "restart"

    if server_epoch is None:
        raise ResumptionEpochViolation(
            "server did not advertise an epoch token; replay-dedup is unprovable"
        )

    if server_epoch != cursor.epoch:
        # State rehydrated but stream renumbered: rebase, do not dedup.
        return "rebase"

    # Same epoch: a first event below the high-water mark is a protocol violation,
    # not a duplicate — the server reset numbering without changing the epoch.
    if first_event_id <= cursor.last_event_id:
        raise ResumptionEpochViolation(
            f"epoch {server_epoch!r} stable but first_event_id {first_event_id} "
            f"<= high-water {cursor.last_event_id}; numbering reset without epoch change"
        )

    return "resume"
