"""
qwen_proxy 日志配置

默认 INFO 级别，日志文件：
- logs/info.log   (INFO 及以上)
- logs/error.log  (ERROR 及以上)
- logs/debug.log  (DEBUG 及以上，全量日志)
"""

import logging
from pathlib import Path


def setup_logging(
    log_dir: str | Path = "logs",
    level: int = logging.INFO,
) -> logging.Logger:
    """
    初始化 qwen_proxy 日志系统。

    Args:
        log_dir: 日志目录，默认 logs/
        level: 根日志级别，默认 INFO
    """
    log_path = Path(log_dir)
    log_path.mkdir(parents=True, exist_ok=True)

    logger = logging.getLogger("qwen_proxy")
    logger.setLevel(logging.DEBUG)  # logger 本身设为 DEBUG，由各 handler 过滤

    # 避免重复添加 handler
    if logger.handlers:
        return logger

    formatter = logging.Formatter(
        fmt="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S",
    )

    # DEBUG handler → logs/debug.log (全量)
    debug_handler = logging.FileHandler(log_path / "debug.log", encoding="utf-8")
    debug_handler.setLevel(logging.DEBUG)
    debug_handler.setFormatter(formatter)
    logger.addHandler(debug_handler)

    # INFO handler → logs/info.log
    info_handler = logging.FileHandler(log_path / "info.log", encoding="utf-8")
    info_handler.setLevel(logging.INFO)
    info_handler.setFormatter(formatter)
    logger.addHandler(info_handler)

    # ERROR handler → logs/error.log
    error_handler = logging.FileHandler(log_path / "error.log", encoding="utf-8")
    error_handler.setLevel(logging.ERROR)
    error_handler.setFormatter(formatter)
    logger.addHandler(error_handler)

    # 控制台 handler (受 level 参数控制)
    console_handler = logging.StreamHandler()
    console_handler.setLevel(level)
    console_handler.setFormatter(formatter)
    logger.addHandler(console_handler)

    return logger
