# -*- coding: utf-8 -*-
"""
统一日志配置模块
提供标准化的日志配置和管理
"""

import logging
import sys
from typing import Optional, Union
from pathlib import Path


class LogConfig:
    """日志配置类"""

    DEFAULT_LOG_FORMAT: str = (
        "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
    )
    DEFAULT_DATE_FORMAT: str = "%Y-%m-%d %H:%M:%S"
    DEFAULT_LEVEL: int = logging.INFO

    @classmethod
    def setup(
        cls,
        level: Union[int, str] = DEFAULT_LEVEL,
        log_format: str = DEFAULT_LOG_FORMAT,
        date_format: str = DEFAULT_DATE_FORMAT,
        log_file: Optional[Union[str, Path]] = None,
        console: bool = True,
    ) -> None:
        """
        配置全局日志系统

        Args:
            level: 日志级别，默认 INFO
            log_format: 日志格式字符串
            date_format: 日期格式字符串
            log_file: 日志文件路径，可选
            console: 是否输出到控制台，默认 True

        Example:
            >>> LogConfig.setup(level=logging.DEBUG, log_file="app.log")
        """
        if isinstance(level, str):
            level = getattr(logging, level.upper(), cls.DEFAULT_LEVEL)

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

        formatter = logging.Formatter(log_format, date_format)

        if root_logger.handlers:
            root_logger.handlers.clear()

        if console:
            console_handler = logging.StreamHandler(sys.stdout)
            console_handler.setFormatter(formatter)
            root_logger.addHandler(console_handler)

        if log_file is not None:
            log_path = Path(log_file)
            log_path.parent.mkdir(parents=True, exist_ok=True)
            file_handler = logging.FileHandler(log_path, encoding="utf-8")
            file_handler.setFormatter(formatter)
            root_logger.addHandler(file_handler)

    @classmethod
    def get_logger(cls, name: str) -> logging.Logger:
        """
        获取命名日志记录器

        Args:
            name: 日志记录器名称

        Returns:
            logging.Logger: 日志记录器实例

        Example:
            >>> logger = LogConfig.get_logger("my_module")
            >>> logger.info("Hello, world!")
        """
        return logging.getLogger(name)


def get_logger(name: str) -> logging.Logger:
    """
    便捷函数：获取命名日志记录器

    Args:
        name: 日志记录器名称

    Returns:
        logging.Logger: 日志记录器实例
    """
    return LogConfig.get_logger(name)
