# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-broken-session-affinity-invariant-when-an-http-native-mcp-server-multiplexes-statelessly-across-edge-replicas.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-broken-session-affinity-invariant-when-an-http-native-mcp-server-multiplexes-statelessly-across-edge-replicas.warrant.json
# Markdown SHA-256:   3bf2ecdd85661de20ca7a22c8ae57f32c876baf60003483d7bae9777c27a93ca
# Code AST SHA-256:   8120278a7fa72404a8d1c4cb6315aeab35e04a49bd63fee19fd0050f3853a4ae
# Verified Classes:   SessionAffinityViolation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hmac
import hashlib
import json
import time
from typing import Any


class SessionAffinityViolation(RuntimeError):
    """Raised when a stateless replica cannot resolve an Mcp-Session-Id to the
    negotiated state the client holds, AND the request would otherwise be
    served against fabricated defaults."""
    pass


def resolve_session(
    session_id: str,
    signing_key: bytes,
    replica_local_store: dict[str, dict[str, Any]],
    now: float | None = None,
) -> dict[str, Any]:
    """
    Resolve an Mcp-Session-Id to negotiated state on a stateless edge replica.

    Two legal paths:
      1. Self-contained signed token: verify HMAC, extract state. Works on any replica.
      2. Local store hit: replica happens to hold the session (sticky or warm).

    Anything else MUST raise, never fall back to defaults.
    """
    now = now if now is not None else time.time()

    # Path 1: signed, self-contained token (preferred for stateless multiplexing).
    if session_id.count(".") == 2:
        payload_b64, sig_b64, _ = session_id.split(".")
        expected = hmac.new(
            signing_key, payload_b64.encode(), hashlib.sha256
        ).hexdigest()
        if not hmac.compare_digest(expected, sig_b64):
            raise SessionAffinityViolation(
                f"session {session_id[:16]}... signature mismatch on replica"
            )
        state = json.loads(_b64decode(payload_b64))
        if state["exp"] < now:
            raise SessionAffinityViolation(
                f"session {session_id[:16]}... expired at {state['exp']}"
            )
        return state

    # Path 2: opaque pointer into replica-local store.
    if session_id in replica_local_store:
        return replica_local_store[session_id]

    # No fallback. Fabricating a default session here is the bug this guards.
    raise SessionAffinityViolation(
        f"session {session_id[:16]}... unresolvable on this replica; "
        f"client must re-initialize (return 404, not 200/202)"
    )


def handle_notification(
    session_id: str, signing_key: bytes, store: dict[str, dict[str, Any]]
) -> int:
    """Notifications must NOT return 202 for unresolved sessions."""
    try:
        resolve_session(session_id, signing_key, store)
    except SessionAffinityViolation as e:
        # Force client transport to re-initialize.
        raise SessionAffinityViolation(
            f"notification rejected: {e}"
        ) from e
    return 202


def _b64decode(s: str) -> bytes:
    import base64
    return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))
