# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-streamable-http-sse-resumption-as-a-fresh-capability-negotiation-rather-than-a-transparent-replay.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-streamable-http-sse-resumption-as-a-fresh-capability-negotiation-rather-than-a-transparent-replay.warrant.json
# Markdown SHA-256:   26f510a5b3b2054ceb1e830c0225689e8122f267c80fe49812f7bc3b6dbae678
# Code AST SHA-256:   7a42b5259f68347bd2ed595202960d4d2bac677e4f9ca84f75248dd0312164bc
# Verified Classes:   SessionResumptionAmbiguity
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SessionResumptionAmbiguity(RuntimeError):
    """Raised when a Streamable-HTTP SSE reconnect cannot be classified as
    either a true resume or a fresh session re-establishment."""
    pass


def classify_reconnect(
    request_session_id: str,
    response_session_id: str | None,
    last_event_id_sent: int,
    first_event_id_received: int | None,
    saw_initialize_payload: bool,
    saw_resumption_ack: bool,
) -> str:
    """Return 'resume' or 'reestablish'. Raise on ambiguous state that the
    caller must not paper over with a blind retry."""
    if response_session_id is None:
        # Server omitted the session header entirely: cannot prove continuity.
        raise SessionResumptionAmbiguity(
            "reconnect response omitted Mcp-Session-Id; cannot distinguish "
            "resume from re-establishment"
        )

    if response_session_id != request_session_id:
        # New session id: definitionally a re-establishment, even on 200.
        return "reestablish"

    if saw_initialize_payload:
        # An initialize-shaped message on a "resumed" stream is a lie.
        return "reestablish"

    if saw_resumption_ack:
        return "resume"

    if first_event_id_received is None:
        raise SessionResumptionAmbiguity(
            "no event id observed on resumed stream and no resumption-ack; "
            "server may have silently restarted at id 0"
        )

    if first_event_id_received <= last_event_id_sent:
        # Cursor not honored: server replayed from the beginning or ignored
        # Last-Event-ID. Treat as re-establishment to avoid duplicate effects.
        return "reestablish"

    return "resume"


def resume_or_reinitialize(ctx) -> None:
    verdict = classify_reconnect(
        request_session_id=ctx.sent_session_id,
        response_session_id=ctx.response_session_id,
        last_event_id_sent=ctx.last_event_id,
        first_event_id_received=ctx.first_event_id,
        saw_initialize_payload=ctx.saw_initialize,
        saw_resumption_ack=ctx.saw_ack,
    )
    if verdict == "reestablish":
        # Discard buffered calls; they were bound to the dead session.
        ctx.drop_buffered_outbound()
        ctx.run_initialize_handshake()
        # Re-issue only with idempotency keys derived from pre-disconnect calls.
        for call in ctx.inflight_calls:
            ctx.emit_with_idempotency_key(call, call.pre_disconnect_key)
    elif verdict == "resume":
        ctx.replay_buffered_outbound()
    else:
        raise SessionResumptionAmbiguity(f"unhandled verdict: {verdict}")
