"""Request context management via contextvars."""
from contextvars import ContextVar
from typing import Optional

_request_id: ContextVar[Optional[str]] = ContextVar("request_id", default=None)
_trace_id: ContextVar[Optional[str]] = ContextVar("trace_id", default=None)
_account_id: ContextVar[Optional[str]] = ContextVar("account_id", default=None)
_job_id: ContextVar[Optional[str]] = ContextVar("job_id", default=None)


def set_request_id(value: str) -> None:
    _request_id.set(value or None)


def get_request_id() -> Optional[str]:
    return _request_id.get()


def set_trace_id(value: str) -> None:
    _trace_id.set(value or None)


def get_trace_id() -> Optional[str]:
    return _trace_id.get()


def set_account_id(value: str) -> None:
    _account_id.set(value or None)


def get_account_id() -> Optional[str]:
    return _account_id.get()


def set_job_id(value: str) -> None:
    _job_id.set(value or None)


def get_job_id() -> Optional[str]:
    return _job_id.get()


def clear_context() -> None:
    """Reset all request-scoped context vars. Call in middleware finally blocks."""
    _request_id.set(None)
    _trace_id.set(None)
    _account_id.set(None)
    _job_id.set(None)
