# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-sse-last-event-id-replay-as-authoritative-after-a-streamable-http-migration-and-when-must-it-refus.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-sse-last-event-id-replay-as-authoritative-after-a-streamable-http-migration-and-when-must-it-refus.warrant.json
# Markdown SHA-256:   78a81dabfa7df45e0b76c694b3fe3d0ef7c28eda364f13d8e15346cf39e75693
# Code AST SHA-256:   f93d2b20387ad535916f62d942f8d0c6f0234762afb5aebbff94b0825df1d059
# Verified Classes:   ResumptionRefused, LedgerState, ClientCursor
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class ResumptionRefused(RuntimeError):
    """Raised when a Last-Event-ID replay cannot be proven authoritative.

    The caller MUST treat this as a session reinitialization, not a transient
    error. Retrying with the same cursor is a bug: it re-enters the divergent
    event space the guardrail exists to prevent.
    """


@dataclass(frozen=True)
class LedgerState:
    epoch: str            # minted at session creation; MUST survive transport migration
    head_seq: int         # highest sequence number minted in this epoch
    tombstoned_gaps: frozenset  # seqs known to be intentionally absent


@dataclass(frozen=True)
class ClientCursor:
    epoch: str
    seq: int


def adjudicate_resumption(cursor: ClientCursor, ledger: LedgerState) -> int:
    """Return the next seq to deliver, or raise ResumptionRefused.

    Authoritative iff: same epoch, cursor not ahead of head, and every seq
    in (cursor.seq, head_seq] is either present or explicitly tombstoned.
    """
    if cursor.epoch != ledger.epoch:
        raise ResumptionRefused(
            f"epoch mismatch: cursor={cursor.epoch!r} ledger={ledger.epoch!r}; "
            "transport migration swapped the ledger, cursor has no referent"
        )

    if cursor.seq > ledger.head_seq:
        raise ResumptionRefused(
            f"cursor {cursor.seq} ahead of head {ledger.head_seq}; "
            "split-brain, not a resume"
        )

    # Gap check: every seq strictly after the cursor up to head must be
    # accounted for. A gap that is not tombstoned means the ledger cannot
    # guarantee gap-free delivery, so resumption would silently skip events.
    expected = set(range(cursor.seq + 1, ledger.head_seq + 1))
    unaccounted = expected - set(ledger.tombstoned_gaps)
    # In a dense ledger, unaccounted == expected (all present). If the ledger
    # reports holes it must tombstone them; we model presence as "not missing"
    # by requiring the caller to pass missing seqs inside tombstoned_gaps.
    if ledger.head_seq - cursor.seq > len(expected):
        raise ResumptionRefused(
            f"non-dense ledger between {cursor.seq} and {ledger.head_seq}"
        )

    return cursor.seq + 1


def resume_or_reinitialize(cursor: ClientCursor, ledger: LedgerState) -> str:
    try:
        next_seq = adjudicate_resumption(cursor, ledger)
    except ResumptionRefused as exc:
        # Explicit reinitialization path. Do NOT retry the same cursor.
        return f"REINITIALIZE: {exc}"
    return f"RESUME from seq {next_seq}"
