import logging
import os
from logging.handlers import RotatingFileHandler


class LoggerConfig:
    """A class to configure logging for the Flask application."""

    LOG_DIR = "logs"  # Define the log directory

    @staticmethod
    def init_logger(app):
        """Initializes separate log files for INFO, ERROR, and WARNING levels."""

        # Ensure the logs directory exists
        if not os.path.exists(LoggerConfig.LOG_DIR):
            os.makedirs(LoggerConfig.LOG_DIR)

        # Remove default handlers to prevent duplicate logging
        for handler in app.logger.handlers[:]:
            app.logger.removeHandler(handler)

        # Create separate loggers
        info_logger = LoggerConfig._setup_logger(
            "info_logger", "info.log", logging.INFO, logging.WARNING
        )
        error_logger = LoggerConfig._setup_logger(
            "error_logger", "error.log", logging.ERROR, logging.CRITICAL
        )
        warning_logger = LoggerConfig._setup_logger(
            "warning_logger", "warning.log", logging.WARNING, logging.WARNING
        )

        # Attach handlers to Flask app logger
        app.logger.addHandler(info_logger)
        app.logger.addHandler(error_logger)
        app.logger.addHandler(warning_logger)

        app.logger.setLevel(logging.DEBUG)  # Set lowest level to capture all logs
        app.logger.info("Logger has been initialized for Flask application.")

    @staticmethod
    def _setup_logger(name, filename, level, max_level):
        """Helper method to configure loggers for specific levels."""
        logger = logging.getLogger(name)
        logger.setLevel(level)
        log_file_path = os.path.join(LoggerConfig.LOG_DIR, filename)
        log_handler = RotatingFileHandler(log_file_path, maxBytes=100000, backupCount=3)
        log_handler.setLevel(level)
        log_formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
        log_handler.setFormatter(log_formatter)
        log_handler.addFilter(lambda record: level <= record.levelno <= max_level)
        logger.addHandler(log_handler)
        return log_handler
