import logging
import functools
from .singleton import Singleton

class CustomLogger(Singleton):
    """
    Singleton logger class that initializes a logger with a specified name and log file.
    It provides a method to log entry and exit of functions.
    """

    def __init__(self, name='main', log_file=None, level=logging.INFO):
        if hasattr(self, '_initialized') and self._initialized:
            return  # すでに初期化済みなら何もしない
            # self.logger.setLevel(level)

        self.logger = logging.getLogger(name)
        self.logger.setLevel(level)
        self.logger.propagate = False

        formatter = logging.Formatter(
            '%(asctime)s %(levelname)s [%(filename)s:%(lineno)3d]: %(message)s'
        )

        # Console handler
        ch = logging.StreamHandler()
        ch.setFormatter(formatter)
        self.logger.addHandler(ch)

        # File handler
        if log_file:
            fh = logging.FileHandler(log_file, encoding='utf-8')
            fh.setFormatter(formatter)
            self.logger.addHandler(fh)

        self._initialized = True


    def get_logger(self):
        return self.logger

    def log_entry_exit(self, func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            self.logger.info(f"Enter: {func.__qualname__}")
            result = func(*args, **kwargs)
            self.logger.info(f"Exit: {func.__qualname__}")
            return result
        return wrapper





def get_logger(name='main', log_file=None, level=logging.INFO):
    custom_logger = CustomLogger(name, log_file, level)
    return custom_logger.get_logger()
