# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-an-mcp-last-event-id-resume-as-a-fresh-session-rather-than-a-continuation.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-an-mcp-last-event-id-resume-as-a-fresh-session-rather-than-a-continuation.warrant.json
# Markdown SHA-256:   dccd145453dd802d69841d1c63f30c47636f275ec57c2fcf1115fe527400d5b6
# Code AST SHA-256:   5135bb54352b68406dc537de4fb23126fbd109c3416208b561d76c4689287487
# Verified Classes:   SessionCursorMismatch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SessionCursorMismatch(RuntimeError):
    """Raised when a Last-Event-ID cursor cannot be attributed to the resolved session."""
    pass


def resolve_resume(
    presented_session_id: str | None,
    last_event_id: str | None,
    live_sessions: dict[str, "Session"],
    retained_window: int,
) -> tuple["Session", int | None]:
    """
    Decide whether a reconnect is a continuation or a fresh subscription.
    Returns (session, replay_from_seq_or_None).
    """
    if presented_session_id is None:
        # No session handle: cannot be a continuation.
        return new_session(), None

    session = live_sessions.get(presented_session_id)
    if session is None:
        # Session is dead. The cursor is from a prior incarnation and must not
        # be replayed against a freshly minted session.
        return new_session(), None

    if last_event_id is None:
        return session, None

    seq = parse_event_id(last_event_id)
    if seq is None:
        raise SessionCursorMismatch(
            f"unparseable Last-Event-ID {last_event_id!r} for session {presented_session_id}"
        )

    owner = event_id_session_owner(last_event_id)
    if owner != presented_session_id:
        # Cursor belongs to a different session: tenant-isolation boundary.
        raise SessionCursorMismatch(
            f"Last-Event-ID {last_event_id!r} owned by {owner!r}, "
            f"presented under session {presented_session_id!r}"
        )

    if seq < session.high_water - retained_window:
        # Cursor is outside the retained window; the client has an unrecoverable gap.
        return session, None

    return session, seq
