import os
import atexit
import logging
from queue import Queue
from logging.handlers import QueueHandler, QueueListener


def setup_async_multiprocess_logger(
        log_dir="logs",
        log_name="bid-service.log",
        level=logging.INFO
):
    if getattr(logging, "_async_logger_initialized", False):
        return logging.getLogger()

    os.makedirs(log_dir, exist_ok=True)
    log_path = os.path.join(log_dir, log_name)

    log_queue = Queue(-1)

    formatter = logging.Formatter(
        "%(asctime)s bid-service %(levelname)s TID:%(trace_id)s %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S"
    )

    file_handler = ConcurrentRotatingFileHandler(
        filename=log_path,
        maxBytes=10 * 1024 * 1024,
        backupCount=5,
        encoding="utf-8"
    )
    file_handler.setFormatter(formatter)
    file_handler.setLevel(level)

    console_handler = logging.StreamHandler()
    console_handler.setFormatter(formatter)
    console_handler.setLevel(level)

    queue_handler = QueueHandler(log_queue)

    root_logger = logging.getLogger()
    root_logger.setLevel(level)
    root_logger.handlers.clear()
    root_logger.addHandler(queue_handler)

    listener = QueueListener(
        log_queue,
        file_handler,
        console_handler,
        respect_handler_level=True
    )
    listener.start()
    atexit.register(listener.stop)

    logging._async_logger_initialized = True
    return root_logger


logging = setup_async_multiprocess_logger
