"""Structured logging with context variables.

Provide context propagation for request tracing across async operations.
"""

from __future__ import annotations

from contextvars import ContextVar
from uuid import uuid4

# Context variables for request tracing
request_id_var: ContextVar[str | None] = ContextVar("request_id", default=None)
user_id_var: ContextVar[str | None] = ContextVar("user_id", default=None)
workspace_id_var: ContextVar[str | None] = ContextVar("workspace_id", default=None)


def generate_request_id() -> str:
    """Generate a unique request ID for correlation.

    Returns:
        UUID string for the request.
    """
    return str(uuid4())


def get_request_id() -> str | None:
    """Get the current request ID from context.

    Returns:
        Request ID if set, None otherwise.
    """
    return request_id_var.get()


def get_user_id() -> str | None:
    """Get the current user ID from context.

    Returns:
        User ID if set, None otherwise.
    """
    return user_id_var.get()


def get_workspace_id() -> str | None:
    """Get the current workspace ID from context.

    Returns:
        Workspace ID if set, None otherwise.
    """
    return workspace_id_var.get()


def get_logging_context() -> dict[str, str | None]:
    """Get all context variables as a dictionary.

    Useful for including in log records.

    Returns:
        Dictionary with request_id, user_id, workspace_id.
    """
    return {
        "request_id": request_id_var.get(),
        "user_id": user_id_var.get(),
        "workspace_id": workspace_id_var.get(),
    }
