import logging
import os
import sys
import shutil


class LogManager:
    # 运行根目录：打包后取 exe 目录；源码运行取项目目录
    if getattr(sys, "frozen", False):
        projectRoot = os.path.dirname(sys.executable)
    else:
        projectRoot = os.path.dirname(os.path.dirname(__file__))

    logDir = os.path.join(projectRoot, "log")
    _loggers = {}

    @classmethod
    def _setupLogger(cls, udid, name, logName, level=logging.INFO):
        """创建或获取 logger，并绑定到文件"""
        deviceLogDir = os.path.join(cls.logDir, udid)
        os.makedirs(deviceLogDir, exist_ok=True)
        logFile = os.path.join(deviceLogDir, logName)

        logger_name = f"{udid}_{name}"
        logger = logging.getLogger(logger_name)
        logger.setLevel(level)

        # 避免重复添加 handler
        if not any(
            isinstance(h, logging.FileHandler) and h.baseFilename == os.path.abspath(logFile)
            for h in logger.handlers
        ):
            fileHandler = logging.FileHandler(logFile, mode="a", encoding="utf-8")
            formatter = logging.Formatter(
                "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
                datefmt="%Y-%m-%d %H:%M:%S"
            )
            fileHandler.setFormatter(formatter)
            logger.addHandler(fileHandler)

        return logger

    @classmethod
    def info(cls, text, udid):
        cls._setupLogger(udid, "infoLogger", "info.log", level=logging.INFO).info(f"[{udid}] {text}")

    @classmethod
    def warning(cls, text, udid):
        cls._setupLogger(udid, "warningLogger", "warning.log", level=logging.WARNING).warning(f"[{udid}] {text}")

    @classmethod
    def error(cls, text, udid):
        cls._setupLogger(udid, "errorLogger", "error.log", level=logging.ERROR).error(f"[{udid}] {text}")

    @classmethod
    def clearLogs(cls):
        """启动时清空 log 目录"""
        print("开始清空日志...")

        # 关闭所有 handler
        for name, logger in logging.Logger.manager.loggerDict.items():
            if isinstance(logger, logging.Logger):
                for handler in logger.handlers[:]:
                    try:
                        handler.close()
                    except:
                        pass
                    logger.removeHandler(handler)

        # 删除并重建日志目录
        if os.path.exists(cls.logDir):
            shutil.rmtree(cls.logDir)
            print(f"删除了 {cls.logDir}")
        os.makedirs(cls.logDir, exist_ok=True)
        print(f"重新创建了 {cls.logDir}")
        print("日志清空完成")
