"""
ロギング機能を提供するモジュール
アプリケーション全体で一貫したログ記録を実現します。
"""

import logging
from logging.handlers import RotatingFileHandler
from typing import Optional
import sys
import os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')))
from config.config import config

class Logger:
    _instance: Optional['Logger'] = None
    
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._instance._initialize_logger()
        return cls._instance
    
    def _initialize_logger(self):
        """ロガーの初期化"""
        self.logger = logging.getLogger('status_management')
        self.logger.setLevel(logging.DEBUG)
        
        # ログフォーマットの設定
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
        )
        
        # ファイルハンドラの設定
        log_file = config.get_file_path('log_file')
        file_handler = RotatingFileHandler(
            log_file,
            maxBytes=10*1024*1024,  # 10MB
            backupCount=5
        )
        file_handler.setLevel(logging.DEBUG)
        file_handler.setFormatter(formatter)
        
        # ストリームハンドラの設定（コンソール出力）
        stream_handler = logging.StreamHandler()
        stream_handler.setLevel(logging.INFO)
        stream_handler.setFormatter(formatter)
        
        # ハンドラの追加
        self.logger.addHandler(file_handler)
        self.logger.addHandler(stream_handler)
    
    def debug(self, message: str):
        """デバッグレベルのログを記録"""
        self.logger.debug(message)
    
    def info(self, message: str):
        """情報レベルのログを記録"""
        self.logger.info(message)
    
    def warning(self, message: str):
        """警告レベルのログを記録"""
        self.logger.warning(message)
    
    def error(self, message: str, exc_info: bool = True):
        """エラーレベルのログを記録"""
        self.logger.error(message, exc_info=exc_info)
    
    def critical(self, message: str, exc_info: bool = True):
        """クリティカルレベルのログを記録"""
        self.logger.critical(message, exc_info=exc_info)

# シングルトンインスタンスを作成
logger = Logger()
