# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-streamable-http-sse-to-websocket-upgrade-as-non-resumable-after-a-last-event-id-replay-gap.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-streamable-http-sse-to-websocket-upgrade-as-non-resumable-after-a-last-event-id-replay-gap.warrant.json
# Markdown SHA-256:   adda18f02de32598856fd34a74b865f5d41ad86a2bbd1c94e1adb116b86325e0
# Code AST SHA-256:   bf936ce23fadb39bd248f143add9dfef2886c655499b7badd9b6725506a77a42
# Verified Classes:   ResumeGapError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ResumeGapError(RuntimeError):
    """Raised when an SSE->WebSocket upgrade leaves a non-replayable gap
    between the client's last-seen event ID and the server high-water mark."""
    pass


def validate_upgrade_resume(
    last_seen_id: int,
    hello: dict,
    replay: dict,
    idle_timeout_seconds: float,
) -> int:
    """
    Gate the tool-call state machine across an MCP SSE->WebSocket upgrade.

    Returns the new cursor (highest contiguous processed ID) on success.
    Raises ResumeGapError if the gap is non-empty and not explicitly replayed.
    """
    high_water = hello.get("high_water")
    if high_water is None:
        # Transport cannot prove gap emptiness; refuse to advance.
        raise ResumeGapError(
            f"upgrade at id={last_seen_id} advertises no high_water; "
            "treating upgrade as non-resumable"
        )

    high_water = int(high_water)
    if high_water < last_seen_id:
        raise ResumeGapError(
            f"server high_water {high_water} < client cursor {last_seen_id}; "
            "cursor ownership violated"
        )

    if high_water == last_seen_id:
        return last_seen_id  # gap empty, safe to continue

    replayed = replay.get("replayed_ids")
    if replayed is None:
        raise ResumeGapError(
            f"gap ({last_seen_id}, {high_water}] exists but server returned "
            "no explicit replayed_ids; 'resumed:true' is not sufficient evidence"
        )

    replayed_set = {int(x) for x in replayed}
    expected = set(range(last_seen_id + 1, high_water + 1))
    missing = expected - replayed_set
    if missing:
        raise ResumeGapError(
            f"gap ({last_seen_id}, {high_water}] not fully replayed; "
            f"missing ids={sorted(missing)[:8]}...; "
            "re-issue originating tools/call with idempotency key"
        )

    # Gap fully replayed; advance cursor to high_water after processing replay.
    return high_water
