import logging
import os
from datetime import datetime
from logging.handlers import RotatingFileHandler

from qgis.core import Qgis, QgsMessageLog


class KFRMLogger:
    _logger = None

    @classmethod
    def _initialize(cls):
        if cls._logger is None:
            # Set log directory to C:\temp
            log_dir = r"C:\temp"

            # Create log directory if it doesn't exist
            os.makedirs(log_dir, exist_ok=True)

            # Create timestamp for log filename
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            log_file = os.path.join(log_dir, f"kfrm_tool_log_{timestamp}.log")

            # Configure logger
            cls._logger = logging.getLogger("KFRMLogger")
            cls._logger.setLevel(logging.DEBUG)

            # Create rotating file handler
            file_handler = RotatingFileHandler(
                log_file,
                maxBytes=10 * 1024 * 1024,  # 10MB
                backupCount=5,
            )

            # Create custom formatter for both handlers
            formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
            file_handler.setFormatter(formatter)

            # Add file handler to logger
            cls._logger.addHandler(file_handler)

            # Create a custom handler for QgsMessageLog
            class QgsLogHandler(logging.Handler):
                def emit(self, record):
                    msg = self.format(record)
                    level = Qgis.Info
                    if record.levelno >= logging.ERROR:
                        level = Qgis.Critical
                    elif record.levelno >= logging.WARNING:
                        level = Qgis.Warning
                    QgsMessageLog.logMessage(msg, "KFRM Tool", level)

            # Add QgsMessageLog handler
            qgis_handler = QgsLogHandler()
            qgis_handler.setFormatter(formatter)
            cls._logger.addHandler(qgis_handler)

    @classmethod
    def debug(cls, message):
        cls._initialize()
        cls._logger.debug(message)

    @classmethod
    def info(cls, message):
        cls._initialize()
        cls._logger.info(message)

    @classmethod
    def warning(cls, message):
        cls._initialize()
        cls._logger.warning(message)

    @classmethod
    def error(cls, message):
        cls._initialize()
        cls._logger.error(message)

    @classmethod
    def critical(cls, message):
        cls._initialize()
        cls._logger.critical(message)

    @classmethod
    def exception(cls, message):
        cls._initialize()
        cls._logger.exception(message)


# Usage example:
# from logger import KFRMLogger
# KFRMLogger.info("Info message")
# KFRMLogger.debug("Debug message")
# KFRMLogger.warning("Warning message")
# KFRMLogger.error("Error message")
# KFRMLogger.critical("Critical message")
