# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abandon-mcp-http-native-transport-session-resumption-rather-than-retry-the-last-event-id-stream.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abandon-mcp-http-native-transport-session-resumption-rather-than-retry-the-last-event-id-stream.warrant.json
# Markdown SHA-256:   7234601170ca17ffaf8d28e8c497c718e2bbc329dfc00a7b938471d2a53a05ca
# Code AST SHA-256:   5fa761be9c1580d3931cd640e098e77dd93635e27e8afb89761fe35d351f5905
# Verified Classes:   UnreplayableCursorError, SessionWedgedError, ResumeOutcome, ResumeResponse
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from enum import Enum


class UnreplayableCursorError(RuntimeError):
    """Raised when Last-Event-ID cannot be mapped to replayable session history."""
    pass


class SessionWedgedError(RuntimeError):
    """Raised when retry budget is exhausted without progress."""
    pass


class ResumeOutcome(Enum):
    REPLAYED = "replayed"
    BACKPRESSURE = "backpressure"
    UNREPLAYABLE = "unreplayable"
    GAP_DETECTED = "gap_detected"


@dataclass
class ResumeResponse:
    status: int
    body_kind: str          # "replay" | "buffer_full" | "cursor_unknown" | "replay"
    retry_after_s: float = 0.0
    replayed_ids: tuple = ()


def classify(resp: ResumeResponse, expected_next_id: int) -> ResumeOutcome:
    if resp.status in (404, 410) or resp.body_kind == "cursor_unknown":
        return ResumeOutcome.UNREPLAYABLE
    if resp.status in (429, 503) or resp.body_kind == "buffer_full":
        return ResumeOutcome.BACKPRESSURE
    if resp.status == 200:
        ids = resp.replayed_ids
        if not ids or ids[0] != expected_next_id:
            return ResumeOutcome.GAP_DETECTED
        return ResumeOutcome.REPLAYED
    return ResumeOutcome.BACKPRESSURE


def resume_stream(send_resume, last_event_id: int, expected_next_id: int,
                  max_backpressure_retries: int = 5) -> ResumeOutcome:
    backpressure_attempts = 0
    while True:
        resp = send_resume(last_event_id)
        outcome = classify(resp, expected_next_id)

        if outcome is ResumeOutcome.REPLAYED:
            return outcome

        if outcome in (ResumeOutcome.UNREPLAYABLE, ResumeOutcome.GAP_DETECTED):
            # Cursor is dead. Do NOT retry it. Force a fresh session handshake.
            raise UnreplayableCursorError(
                f"Last-Event-ID={last_event_id} not replayable "
                f"(outcome={outcome.value}, status={resp.status}); "
                f"re-initialize session and reconcile state out-of-band"
            )

        # BACKPRESSURE: wait on the existing stream, retry same cursor, bounded.
        backpressure_attempts += 1
        if backpressure_attempts > max_backpressure_retries:
            raise SessionWedgedError(
                f"backpressure retries exhausted for cursor {last_event_id}"
            )
        time.sleep(resp.retry_after_s or 0.5)


def handle_resume_or_abandon(send_resume, last_event_id: int,
                             expected_next_id: int) -> str:
    try:
        resume_stream(send_resume, last_event_id, expected_next_id)
        return "resumed"
    except UnreplayableCursorError:
        # Only correct recovery: discard cursor, new session, reconcile.
        return "reinitialized"
    except SessionWedgedError:
        return "escalate_to_operator"
