# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-last-event-id-resumption-as-invalid-and-abort-the-stream-rather-than-replay-from-the-session-store.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-last-event-id-resumption-as-invalid-and-abort-the-stream-rather-than-replay-from-the-session-store.warrant.json
# Markdown SHA-256:   b36de302f95bc4d85af7b2ca46b1e6c79364d778a4058ab140ee0122c7ad40e9
# Code AST SHA-256:   e073ddd6b39a4b2cf46baf21a966bfd70e11063036c42127d86c00e3dc3826be
# Verified Classes:   ResumptionRejected, Event, SessionRecord
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class ResumptionRejected(RuntimeError):
    """Raised when a Last-Event-ID resumption cannot be proven safe."""
    pass


@dataclass(frozen=True)
class Event:
    event_id: str          # format: "<session_id>:<monotonic_seq>"
    session_id: str
    seq: int
    payload: dict


@dataclass
class SessionRecord:
    session_id: str
    principal: str
    live: bool
    min_retained_seq: int  # lowest seq still in the ring buffer for this session
    head_seq: int


def resume_stream(
    presented_session_id: str,
    presented_principal: str,
    last_event_id: str,
    sessions: dict[str, SessionRecord],
    buffer: list[Event],
) -> list[Event]:
    """Return events to replay, or raise ResumptionRejected.

    Invariant: replay is permitted only when the event ID is session-bound,
    the session is live, the principal matches, and no events between the
    requested ID and head were truncated.
    """
    try:
        id_session, id_seq_str = last_event_id.split(":", 1)
        id_seq = int(id_seq_str)
    except (ValueError, AttributeError) as exc:
        raise ResumptionRejected(
            f"malformed Last-Event-ID {last_event_id!r}: {exc}"
        ) from exc

    # 1. Event ID must bind to the session being resumed.
    if id_session != presented_session_id:
        raise ResumptionRejected(
            f"event {last_event_id} belongs to session {id_session}, "
            f"client presented {presented_session_id}"
        )

    # 2. Session must still exist and be live; buffer presence is not enough.
    record = sessions.get(presented_session_id)
    if record is None or not record.live:
        raise ResumptionRejected(
            f"session {presented_session_id} absent or expired; "
            "buffer retention does not authorize replay"
        )

    # 3. Principal must match the session creator.
    if record.principal != presented_principal:
        raise ResumptionRejected(
            f"principal mismatch on session {presented_session_id}"
        )

    # 4. Contiguity: the requested seq must not have been truncated.
    if id_seq < record.min_retained_seq - 1:
        raise ResumptionRejected(
            f"gap: requested seq {id_seq} truncated; "
            f"ring retains from {record.min_retained_seq}"
        )

    if id_seq > record.head_seq:
        raise ResumptionRejected(
            f"requested seq {id_seq} ahead of head {record.head_seq}"
        )

    replay = [
        e for e in buffer
        if e.session_id == presented_session_id and e.seq > id_seq
    ]

    # Defensive: replayed set must be strictly contiguous from id_seq+1.
    expected = id_seq + 1
    for e in replay:
        if e.seq != expected:
            raise ResumptionRejected(
                f"non-contiguous replay: expected seq {expected}, got {e.seq}"
            )
        expected += 1

    return replay
