"""Module for Logging Errors"""

import logging
import logging.config
import os
from logging.handlers import RotatingFileHandler

import yaml

yaml_config_file = "configs/logging_config.yaml"


class ServiceLogger:
    """Logger class for logging messages with optional error information and traceback."""

    _instance = None  # Singleton instance

    def __new__(
        cls, log_file="logs/service.log", max_size_bytes=5242880, backup_count=5
    ):
        if cls._instance is None:
            cls._instance = super(ServiceLogger, cls).__new__(cls)
            cls._instance._initialize(yaml_config_file)
        return cls._instance

    def _initialize(self, config_file):
        with open(config_file, "r") as f:
            config_text = yaml.safe_load(f.read())

            # Ensure the log directory exists
            log_filename = config_text["handlers"]["file"]["filename"]
            os.makedirs(os.path.dirname(log_filename), exist_ok=True)

            logging.config.dictConfig(config_text)

    def get_logger(self, name=None):
        """Return the logger instance."""
        if name is None:
            return logging.getLogger()  # Return root logger
        return logging.getLogger(name)


# Initialize logging early
XCM_logger = logging.getLogger()
# Log a message outside the function
XCM_logger.info("Logging system initialized.")

if __name__ == "__main__":
    XCM_logger.info("Script execution started.")

    try:
        XCM_logger.info("TEST")
        raise ValueError("Example error")
    except ValueError as e:
        XCM_logger.error("An error occurred.", exc_info=True)

    XCM_logger.info("Completed processing.")
