import logging
import os
import sys
import shutil
from pathlib import Path


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="system"):
        cls._setupLogger(udid, "infoLogger", "info.log", level=logging.INFO).info(f"[{udid}] {text}")

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

    @classmethod
    def error(cls, text, udid="system"):
        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 Exception:
                        pass
                    logger.removeHandler(handler)

        # 仅删除目录里的所有文件和子目录
        log_path = Path(cls.logDir)
        if log_path.exists():
            for item in log_path.iterdir():
                if item.is_file():
                    item.unlink()
                elif item.is_dir():
                    import shutil
                    shutil.rmtree(item)

        print("日志清空完成")
