"""统一日志配置模块"""

import logging
import os
import sys
from pathlib import Path


class LoggerConfig:
    """日志配置管理类"""

    def __init__(self, logs_dir: str = None):
        if logs_dir:
            self.logs_dir = Path(logs_dir)
        else:
            project_root = Path(__file__).parent.parent
            self.logs_dir = project_root / "logs"
        self.logs_dir.mkdir(parents=True, exist_ok=True)
        self.log_format = "%(asctime)s - %(name)s - %(levelname)s - [%(filename)s:%(lineno)d] - %(message)s"
        self.date_format = "%Y-%m-%d %H:%M:%S"
        self._initialized = False

    def setup_logging(
        self,
        app_name: str = "lzwcai_mcp_agile_db_third",
        log_level: int = logging.INFO,
        console_output: bool = False,
    ) -> logging.Logger:
        """设置系统日志配置。"""
        if self._initialized:
            return logging.getLogger()

        root_logger = logging.getLogger()
        root_logger.setLevel(log_level)

        for handler in root_logger.handlers[:]:
            root_logger.removeHandler(handler)

        formatter = logging.Formatter(self.log_format, self.date_format)

        # 主日志文件
        main_log_file = self.logs_dir / f"{app_name}.log"
        file_handler = logging.FileHandler(main_log_file, encoding="utf-8")
        file_handler.setLevel(log_level)
        file_handler.setFormatter(formatter)
        root_logger.addHandler(file_handler)

        # 错误日志文件
        error_log_file = self.logs_dir / f"{app_name}_error.log"
        error_handler = logging.FileHandler(error_log_file, encoding="utf-8")
        error_handler.setLevel(logging.ERROR)
        error_handler.setFormatter(formatter)
        root_logger.addHandler(error_handler)

        # MCP 使用 stdio 时，控制台日志必须输出到 stderr
        if console_output:
            console_handler = logging.StreamHandler(sys.stderr)
            console_handler.setLevel(log_level)
            console_handler.setFormatter(formatter)
            root_logger.addHandler(console_handler)

        self._initialized = True
        root_logger.info(f"日志系统初始化完成 - 日志目录: {self.logs_dir}")
        return root_logger

    def setup_mcp_logging(self) -> logging.Logger:
        """设置 MCP 专用日志。"""
        return self.create_component_logger("mcp_services", "mcp_services.log", logging.DEBUG)

    def create_component_logger(
        self, component_name: str, log_file: str = None, log_level: int = None
    ) -> logging.Logger:
        """为特定组件创建独立日志器。"""
        logger = logging.getLogger(component_name)
        if log_file:
            component_log_file = self.logs_dir / log_file
            handler = logging.FileHandler(component_log_file, encoding="utf-8")
            handler.setFormatter(logging.Formatter(self.log_format, self.date_format))
            if log_level is not None:
                handler.setLevel(log_level)
            logger.addHandler(handler)
        return logger


logger_config = LoggerConfig()
