"""Request-scoped context helpers for backend clients."""

from __future__ import annotations

from collections.abc import Iterator
from contextlib import contextmanager
from contextvars import ContextVar, Token

_clerk_user_id: ContextVar[str | None] = ContextVar("clerk_user_id", default=None)
_mcp_session_id: ContextVar[str | None] = ContextVar("mcp_session_id", default=None)


def get_clerk_user_id() -> str | None:
    """Return the Clerk user ID for the current request, if available."""
    return _clerk_user_id.get()


def set_clerk_user_id(user_id: str | None) -> Token:
    """Set the Clerk user ID for the current request."""
    return _clerk_user_id.set(user_id)


def reset_clerk_user_id(token: Token) -> None:
    """Reset the Clerk user ID to its previous value."""
    _clerk_user_id.reset(token)


@contextmanager
def clerk_user_context(user_id: str | None) -> Iterator[None]:
    """Context manager for setting the Clerk user ID during a request."""
    token = set_clerk_user_id(user_id)
    try:
        yield
    finally:
        reset_clerk_user_id(token)


def get_mcp_session_id() -> str | None:
    """Return the MCP session ID for the current request, if available."""
    return _mcp_session_id.get()


def set_mcp_session_id(session_id: str | None) -> Token:
    """Set the MCP session ID for the current request."""
    return _mcp_session_id.set(session_id)


def reset_mcp_session_id(token: Token) -> None:
    """Reset the MCP session ID to its previous value."""
    _mcp_session_id.reset(token)


@contextmanager
def mcp_session_context(session_id: str | None) -> Iterator[None]:
    """Context manager for setting the MCP session ID during a request."""
    token = set_mcp_session_id(session_id)
    try:
        yield
    finally:
        reset_mcp_session_id(token)
