import logging
from contextvars import ContextVar

_request_id: ContextVar[str] = ContextVar("request_id", default="-")


def get_request_id() -> str:
    return _request_id.get()


def set_request_id(value: str):
    """Returns the contextvars.Token so the middleware can reset it
    once the request/connection is done — see app.core.middleware."""
    return _request_id.set(value)


def reset_request_id(token) -> None:
    _request_id.reset(token)


class RequestIdLogFilter(logging.Filter):
    """Stamps every log record with the request ID of whatever request
    is in flight on the current asyncio task, so log lines from deep
    inside a service call (e.g. app.services.payments.chapa logging a webhook
    error) can be correlated back to the request that triggered them
    without threading a request_id parameter through every function
    signature in the codebase."""

    def filter(self, record: logging.LogRecord) -> bool:
        record.request_id = get_request_id()
        return True


def configure_logging() -> None:
    """Attaches the request-ID filter and a formatter that includes it
    to the root logger, so every `logging.getLogger(...)` call site
    already in the codebase (yeneb.errors, yeneb.sms, yeneb.chapa,
    etc.) picks it up automatically. Idempotent — safe to call more
    than once (e.g. once from app.main, once from a management
    command) without duplicating handlers."""
    root = logging.getLogger()
    if any(isinstance(f, RequestIdLogFilter) for f in root.filters):
        return

    handler = logging.StreamHandler()
    handler.setFormatter(
        logging.Formatter(
            "%(asctime)s %(levelname)s [%(request_id)s] %(name)s: %(message)s"
        )
    )
    handler.addFilter(RequestIdLogFilter())
    root.addHandler(handler)
    root.setLevel(logging.INFO)
