import logging
import logging.config
import json
from pathlib import Path

import config


class SmartLogger(logging.Logger):
    def _log(
        self,
        level,
        msg,
        args,
        exc_info=None,
        extra=None,
        stack_info=False,
        stacklevel=1,
    ):
        if isinstance(msg, (dict, list)):
            msg = json.dumps(msg, indent=4, ensure_ascii=False, default=str)

        super()._log(
            level,
            msg,
            args,
            exc_info,
            extra,
            stack_info,
            stacklevel + 1,
        )


logging.setLoggerClass(SmartLogger)

log_config_path = Path(f"{config.RELOAD_DIR}/config/logger.ini")
logging.config.fileConfig(log_config_path, disable_existing_loggers=False)
logger = logging.getLogger("medods-to-n3health")


def setLogLevel(level: str = ""):
    match level:
        case "DEBUG":
            loggerLevel = logging.DEBUG
        case "WARNING":
            loggerLevel = logging.WARNING
        case "ERROR":
            loggerLevel = logging.ERROR
        case _:
            loggerLevel = logging.INFO

    root_logger = logging.getLogger()
    for handler in root_logger.handlers:
        handler.setLevel(loggerLevel)

    # Также меняем уровень самого логгера
    logger.setLevel(loggerLevel)
