# pyright: reportOptionalMemberAccess=false
import logging
import sys

from loguru import logger  # type: ignore

log_format = (
    "<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | "
    "<level>{level: <8}</level>|"
    "<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>"
)

logger.remove()
logger.add(sys.stderr, format=log_format, level="INFO")
logger.add(
    "logs/logs/app.log",
    rotation="10 MB",
    retention="7 days",
    format=log_format,
    level="INFO",
    encoding="utf-8",
    enqueue=True,
    backtrace=True,
    diagnose=True,
)


class LoggerWrapper:
    def __init__(self, logger):
        self._logger = logger

    def _log(self, level, message):
        self._logger.opt(depth=2).log(level, message)

    def info(self, message):
        self._log("INFO", message)

    def debug(self, message):
        self._log("DEBUG", message)

    def warning(self, message):
        self._log("WARNING", message)

    def error(self, message):
        self._log("ERROR", message)

    def critical(self, message):
        self._log("CRITICAL", message)

    def __getattr__(self, name):
        return getattr(self._logger, name)


logger = LoggerWrapper(logger)


class InterceptHandler(logging.Handler):
    def emit(self, record):
        try:
            level = logger.original.level(record.levelname).name  # type: ignore
        except ValueError:
            level = record.levelno

        frame, depth = logging.currentframe(), 2
        while frame.f_code.co_filename == logging.__file__:
            frame = frame.f_back
            depth += 1

        logger.original.opt(depth=depth, exception=record.exc_info).log(  # type: ignore
            level, record.getMessage()
        )


logging.basicConfig(handlers=[InterceptHandler()], level=0)

__all__ = ["logger"]


def test_logger():
    logger.info("This is an info message")
    logger.debug("This is a debug message")
    logger.warning("This is a warning message")
    logger.error("This is an error message")
    logger.critical("This is a critical message")


if __name__ == "__main__":
    test_logger()
