# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-resumable-mcp-stream-state-from-replayable-event-log-state-under-http-native-bidirectional-transport.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-resumable-mcp-stream-state-from-replayable-event-log-state-under-http-native-bidirectional-transport.warrant.json
# Markdown SHA-256:   733fe161705f7bbda70b0246b5664fbf2fb77248e2f948e88e5b65db5b9bc994
# Code AST SHA-256:   b17060817efa48a51fec733843b412cb08389de812edc40312cae0b4a4840324
# Verified Classes:   StreamResumptionError, SessionEpochMismatch
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class StreamResumptionError(RuntimeError):
    """Raised when a Last-Event-ID cursor cannot be honored on its stream log."""
    pass


class SessionEpochMismatch(RuntimeError):
    """Raised when a replayed event belongs to an evicted session epoch."""
    pass


def resume_stream(stream_log, session_record, last_event_id, session_epoch):
    """
    Resume an SSE stream for an MCP HTTP-native transport.

    stream_log:    per-stream ring buffer of (event_id, session_epoch, payload),
                   keyed by stream id, NOT by session id.
    session_record: current session state, or None if evicted.
    last_event_id: value of the client's Last-Event-ID header.
    session_epoch: epoch the client believes it is on.
    """
    if stream_log is None:
        # No log for this stream at all: cannot honor the cursor.
        raise StreamResumptionError(
            f"no event log for stream; cannot resume from id={last_event_id}"
        )

    head = stream_log.head_id()
    if last_event_id is not None and last_event_id > head:
        # Client claims to have seen an event the server never emitted.
        raise StreamResumptionError(
            f"resume cursor {last_event_id} exceeds stream head {head}; "
            "log corruption or cross-stream id collision"
        )

    pending = stream_log.events_after(last_event_id)
    if last_event_id is not None and not pending and stream_log.was_truncated_after(last_event_id):
        # Log was trimmed past the cursor: explicit failure, never empty 200.
        raise StreamResumptionError(
            f"cursor {last_event_id} evicted from log (oldest retained "
            f"{stream_log.oldest_id()}); client must re-initialize"
        )

    if session_record is None:
        # Replay-only: session gone, log survives. Deliver then terminate.
        for ev in pending:
            if ev.session_epoch != session_epoch:
                raise SessionEpochMismatch(
                    f"event {ev.event_id} from epoch {ev.session_epoch}, "
                    f"client on epoch {session_epoch}; drop, do not answer"
                )
        return {"mode": "replay_only", "events": pending, "terminal": "session_expired"}

    return {"mode": "live", "events": pending, "terminal": None}
