# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-a-resumable-streamable-http-session-from-a-dead-sse-fallback-during-mcp-transport-negotiation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-a-resumable-streamable-http-session-from-a-dead-sse-fallback-during-mcp-transport-negotiation.warrant.json
# Markdown SHA-256:   585d693e5b92a7642f625325c4642cf7f78fa1e1a2b52e1a3faabaf87d469a09
# Code AST SHA-256:   014ccac1b2b2fd078c5712ad758048d3e1cbccc630610ebf14687e18ac6cdf42
# Verified Classes:   TransportResumeError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class TransportResumeError(RuntimeError):
    """Raised when a streamable-HTTP resume cannot be safely distinguished
    from an SSE-fallback downgrade."""
    pass


def resume_session(state, response):
    # state.mode recorded at initialize: "streamable" or "sse"
    # state.session_id, state.endpoint_url captured at negotiation
    if state.mode != "streamable":
        raise TransportResumeError(
            f"resume attempted on non-streamable mode {state.mode!r}; "
            "must re-probe transport, not resume"
        )
    if not state.session_id:
        raise TransportResumeError(
            "no Mcp-Session-Id recorded; resume is undefined"
        )
    ctype = response.headers.get("Content-Type", "")
    if response.status_code == 404 and "application/json" not in ctype:
        # HTML/redirect 404 => downgrade, not reap
        raise TransportResumeError(
            "404 without JSON-RPC body indicates SSE fallback; "
            "invalidate cached endpoint and re-initialize"
        )
    if response.status_code == 404:
        # JSON-RPC session-gone: safe to re-initialize
        state.invalidate_endpoint()
        return "reinitialize"
    if response.status_code == 200:
        return "resumed"
    raise TransportResumeError(
        f"unexpected resume status {response.status_code}"
    )
