"""日志管理器"""

import logging
import sys
from datetime import datetime
from pathlib import Path
from typing import Optional


class Logger:
    """日志管理器

    提供统一的日志记录功能。
    """

    _instance: Optional['Logger'] = None
    _initialized: bool = False

    def __new__(cls, *args, **kwargs) -> 'Logger':
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

    def __init__(
        self,
        name: str = 'kdtest',
        level: int = logging.INFO,
        log_file: Optional[str] = None,
        console: bool = True
    ):
        if Logger._initialized:
            return

        self._logger = logging.getLogger(name)
        self._logger.setLevel(level)
        self._logger.handlers.clear()

        # 日志格式
        formatter = logging.Formatter(
            '%(asctime)s | %(levelname)-8s | %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S'
        )

        # 控制台处理器
        if console:
            console_handler = logging.StreamHandler(sys.stdout)
            console_handler.setLevel(level)
            console_handler.setFormatter(formatter)
            self._logger.addHandler(console_handler)

        # 文件处理器
        if log_file:
            log_path = Path(log_file)
            log_path.parent.mkdir(parents=True, exist_ok=True)

            file_handler = logging.FileHandler(
                str(log_path),
                encoding='utf-8'
            )
            file_handler.setLevel(level)
            file_handler.setFormatter(formatter)
            self._logger.addHandler(file_handler)

        Logger._initialized = True

    def debug(self, message: str) -> None:
        """调试日志"""
        self._logger.debug(message)

    def info(self, message: str) -> None:
        """信息日志"""
        self._logger.info(message)

    def warning(self, message: str) -> None:
        """警告日志"""
        self._logger.warning(message)

    def error(self, message: str) -> None:
        """错误日志"""
        self._logger.error(message)

    def critical(self, message: str) -> None:
        """严重错误日志"""
        self._logger.critical(message)

    def exception(self, message: str) -> None:
        """异常日志（包含堆栈）"""
        self._logger.exception(message)

    @property
    def logger(self) -> logging.Logger:
        """获取底层 Logger"""
        return self._logger

    @classmethod
    def get_instance(cls) -> 'Logger':
        """获取单例实例"""
        if cls._instance is None:
            cls._instance = cls()
        return cls._instance

    @classmethod
    def setup(
        cls,
        name: str = 'kdtest',
        level: int = logging.INFO,
        log_dir: str = 'result/log'
    ) -> 'Logger':
        """初始化日志系统

        Args:
            name: 日志名称
            level: 日志级别
            log_dir: 日志目录

        Returns:
            Logger: 日志实例
        """
        # 生成日志文件名
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        log_file = f"{log_dir}/{name}_{timestamp}.log"

        return cls(name=name, level=level, log_file=log_file)
