# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-sse-last-event-id-replay-with-streamable-http-mcp-session-id-resumption-when-both-headers-are-present.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-sse-last-event-id-replay-with-streamable-http-mcp-session-id-resumption-when-both-headers-are-present.warrant.json
# Markdown SHA-256:   7bd02e0c2057916609e7d0c67ac901f88bae29a4f5bae55f24c8c117069d2ed6
# Code AST SHA-256:   31ae3d34c4c175a6d3755b5c2ae0941be0e78b89395586319e5d03508ea93631
# Verified Classes:   ResumptionGapError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ResumptionGapError(RuntimeError):
    """Raised when a resume request cannot be satisfied from retained history."""

    def __init__(self, session_id: str, requested_from: int, low_water_mark: int):
        self.session_id = session_id
        self.requested_from = requested_from
        self.low_water_mark = low_water_mark
        super().__init__(
            f"session {session_id}: cannot replay from event {requested_from}; "
            f"oldest retained is {low_water_mark}"
        )


def resolve_resume(
    session_id: str | None,
    last_event_id: int | None,
    session_store: dict,
) -> tuple[int, bool]:
    """Return (replay_from, is_resume) or raise ResumptionGapError.

    Both headers are honored; neither overrides the other.
    """
    if session_id is None:
        # No session identity: cannot resume, treat as fresh stream.
        return (0, False)

    session = session_store.get(session_id)
    if session is None:
        # Session expired/unknown; event id is meaningless without it.
        raise ResumptionGapError(session_id, last_event_id or 0, 0)

    if last_event_id is None:
        # Valid session, no cursor: fresh attach at live head.
        return (session["head"] + 1, False)

    replay_from = last_event_id + 1
    if replay_from < session["low_water_mark"]:
        raise ResumptionGapError(session_id, replay_from, session["low_water_mark"])

    return (replay_from, True)
