import logging
import os

class LogManager:
    # 获取项目根目录
    projectRoot = os.path.dirname(os.path.dirname(__file__))
    logDir = os.path.join(projectRoot, "log")
    infoLogFile = os.path.join(logDir, "info.log")
    warningLogFile = os.path.join(logDir, "warning.log")
    errorLogFile = os.path.join(logDir, "error.log")

    # 类变量，存储日志记录器
    _infoLogger = None
    _warningLogger = None
    _errorLogger = None

    @classmethod
    def _setupLogger(cls, name, logFile, level=logging.INFO):
        """设置日志记录器"""
        os.makedirs(cls.logDir, exist_ok=True)  # 确保日志目录存在
        logger = logging.getLogger(name)
        logger.setLevel(level)
        fileHandler = logging.FileHandler(logFile, mode="a", encoding="utf-8")
        formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
        fileHandler.setFormatter(formatter)
        logger.addHandler(fileHandler)
        return logger

    @classmethod
    def _initializeLoggers(cls):
        """初始化所有日志记录器"""
        if not cls._infoLogger:
            cls._infoLogger = cls._setupLogger("infoLogger", cls.infoLogFile, level=logging.INFO)
        if not cls._warningLogger:
            cls._warningLogger = cls._setupLogger("warningLogger", cls.warningLogFile, level=logging.WARNING)
        if not cls._errorLogger:
            cls._errorLogger = cls._setupLogger("errorLogger", cls.errorLogFile, level=logging.ERROR)

    @classmethod
    def info(cls, text):
        """记录 INFO 级别的日志"""
        cls._initializeLoggers()
        cls._infoLogger.info(text)

    @classmethod
    def warning(cls, text):
        """记录 WARNING 级别的日志"""
        cls._initializeLoggers()
        cls._warningLogger.warning(text)

    @classmethod
    def error(cls, text):
        """记录 ERROR 级别的日志"""
        cls._initializeLoggers()
        cls._errorLogger.error(text)

    @classmethod
    def clearLogs(cls):
        """删除所有日志文件"""
        # 关闭所有日志记录器的处理器
        for logger in [cls._infoLogger, cls._warningLogger, cls._errorLogger]:
            if logger:
                for handler in logger.handlers[:]:  # 使用切片避免在迭代时修改列表
                    handler.close()
                    logger.removeHandler(handler)

        # 删除日志文件
        for logFile in [cls.infoLogFile, cls.warningLogFile, cls.errorLogFile]:
            if os.path.exists(logFile):
                os.remove(logFile)  # 删除文件
        print("所有日志文件已删除")