import sys
from pathlib import Path
from logging import Logger

from loguru import logger


def setup_logger(task_type: str, log_path: str | None = None, is_console: bool = False) -> Logger:
    """ 安装日志系统 """
    if log_path is None:
        log_path = f"logs/{task_type}.log"
    # 确保日志目录存在
    log_dir = Path(log_path).parent
    log_dir.mkdir(parents=True, exist_ok=True)
    # 创建logger实例
    logger_instance = logger.bind(task_type=task_type)
    # 只在首次调用时清理控制台环境
    if not hasattr(setup_logger, '_handlers_added'):
        logger.remove() 
        setup_logger._handlers_added = set()
    # 添加文件输出
    if task_type not in setup_logger._handlers_added:
        # 添加日志文件输出
        logger.add(
            log_path,
            rotation="10 MB",
            retention=5,
            format="{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {extra[task_type]} | {name}:{function}:{line} - {message}",
            level="DEBUG",
            backtrace=True, 
            diagnose=True,
            enqueue=True,  # 多进程安全
            filter=lambda record, task=task_type: record["extra"].get("task_type") == task
        )
        # 添加控制台输出
        if is_console:
            logger.add(
                sys.stderr,
                format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level: <8}</level> | <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>",
                level="INFO",
                backtrace=True,
                diagnose=True,
                enqueue=True,  # 多进程安全
                filter=lambda record, task=task_type: record["extra"].get("task_type") == task
            )
        # 标记已添加
        setup_logger._handlers_added.add(task_type)
    # 返回logger实例
    return logger_instance
