import os
import logging
from datetime import datetime
from typing import Optional

class Logger:
    """统一的日志管理类"""
    
    _instance = None
    _initialized = False
    
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance
    
    def __init__(self):
        if not self._initialized:
            # 创建日志目录
            self.log_dir = os.path.join(os.getenv('APPDATA'), 'Cursor', 'logs')
            os.makedirs(self.log_dir, exist_ok=True)
            
            # 配置根日志记录器
            self.logger = logging.getLogger('CursorTools')
            self.logger.setLevel(logging.INFO)
            
            # 日志格式
            self.formatter = logging.Formatter(
                '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
            )
            
            # 添加处理器
            self._add_handlers()
            
            self._initialized = True
    
    def _add_handlers(self):
        """添加日志处理器"""
        if not self.logger.handlers:
            # 文件处理器
            log_file = os.path.join(
                self.log_dir,
                f'cursor_tools_{datetime.now().strftime("%Y%m%d")}.log'
            )
            fh = logging.FileHandler(log_file, encoding='utf-8')
            fh.setLevel(logging.INFO)
            fh.setFormatter(self.formatter)
            self.logger.addHandler(fh)
            
            # 控制台处理器
            ch = logging.StreamHandler()
            ch.setLevel(logging.INFO)
            ch.setFormatter(self.formatter)
            self.logger.addHandler(ch)
    
    def get_logger(self, name: Optional[str] = None) -> logging.Logger:
        """
        获取日志记录器
        :param name: 日志记录器名称
        :return: 日志记录器实例
        """
        if name:
            return self.logger.getChild(name)
        return self.logger

# 创建全局日志管理器实例
logger = Logger() 