"""
标准化日志格式工具模块
提供统一的日志记录格式和辅助函数
"""
from typing import Optional, List, Dict, Any
from loguru import logger


class LogFormatter:
    """标准化日志格式化工具"""
    
    @staticmethod
    def format_success(operation: str, details: Optional[str] = None) -> str:
        """
        格式化成功消息
        
        Args:
            operation: 操作名称
            details: 详细信息
            
        Returns:
            格式化的成功消息
        """
        if details:
            return f"✅ {operation} - {details}"
        return f"✅ {operation}"
    
    @staticmethod
    def format_error(operation: str, error: Exception) -> str:
        """
        格式化错误消息
        
        Args:
            operation: 操作名称
            error: 异常对象
            
        Returns:
            格式化的错误消息
        """
        return f"❌ {operation}失败: {error}"
    
    @staticmethod
    def format_warning(message: str, suggestion: Optional[str] = None) -> str:
        """
        格式化警告消息
        
        Args:
            message: 警告消息
            suggestion: 建议操作
            
        Returns:
            格式化的警告消息
        """
        if suggestion:
            return f"⚠️ {message} - {suggestion}"
        return f"⚠️ {message}"
    
    @staticmethod
    def format_info(operation: str, details: Optional[str] = None) -> str:
        """
        格式化信息消息
        
        Args:
            operation: 操作名称
            details: 详细信息
            
        Returns:
            格式化的信息消息
        """
        if details:
            return f"ℹ️ {operation} - {details}"
        return f"ℹ️ {operation}"
    
    @staticmethod
    def format_debug(component: str, message: str) -> str:
        """
        格式化调试消息
        
        Args:
            component: 组件名称
            message: 调试消息
            
        Returns:
            格式化的调试消息
        """
        return f"[{component}] {message}"


class OperationLogger:
    """操作日志记录器 - 提供统一的操作日志记录接口"""
    
    def __init__(self, operation_name: str):
        """
        初始化操作日志记录器
        
        Args:
            operation_name: 操作名称
        """
        self.operation_name = operation_name
        self.formatter = LogFormatter()
    
    def log_start(self, details: Optional[str] = None):
        """记录操作开始"""
        message = f"开始 {self.operation_name}"
        if details:
            message += f" - {details}"
        logger.info(message)
    
    def log_success(self, details: Optional[str] = None):
        """记录操作成功"""
        logger.info(self.formatter.format_success(self.operation_name, details))
    
    def log_error(self, error: Exception, log_traceback: bool = True):
        """记录操作失败"""
        logger.error(self.formatter.format_error(self.operation_name, error))
        if log_traceback:
            import traceback
            logger.error(traceback.format_exc())
    
    def log_warning(self, message: str, suggestion: Optional[str] = None):
        """记录警告"""
        logger.warning(self.formatter.format_warning(message, suggestion))
    
    def log_progress(self, current: int, total: int, item_name: str = "项"):
        """记录进度"""
        logger.info(f"{self.operation_name} 进度: {current}/{total} {item_name}")


def log_retrieval_result(mode: str, count: int, operation_type: str = "检索"):
    """
    记录检索结果的标准化日志
    
    Args:
        mode: 检索模式
        count: 检索到的文档数量
        operation_type: 操作类型（检索/查询）
    """
    logger.info(
        LogFormatter.format_success(
            f"{operation_type}完成",
            f"检索模式: {mode}, 检索到 {count} 个相关文档片段"
        )
    )


def log_bm25_status(is_enabled: bool, is_loaded: bool):
    """
    记录BM25状态的标准化日志
    
    Args:
        is_enabled: BM25是否启用
        is_loaded: BM25检索器是否已加载
    """
    if is_enabled and is_loaded:
        logger.info(LogFormatter.format_success("BM25检索器", "已启用且已加载"))
    elif is_enabled and not is_loaded:
        logger.warning(
            LogFormatter.format_warning(
                "BM25检索器已启用但未加载",
                "将回退到纯向量检索"
            )
        )
    else:
        logger.debug("BM25检索器未启用")


def log_index_operation(operation: str, count: Optional[int] = None, path: Optional[str] = None):
    """
    记录索引操作的标准化日志
    
    Args:
        operation: 操作类型（创建/加载/保存/删除）
        count: 文档数量（可选）
        path: 路径（可选）
    """
    details_parts = []
    if count is not None:
        details_parts.append(f"文档数: {count}")
    if path:
        details_parts.append(f"路径: {path}")
    
    details = ", ".join(details_parts) if details_parts else None
    logger.info(LogFormatter.format_success(f"{operation}索引", details))


def log_config_change(config_key: str, old_value: Any, new_value: Any):
    """
    记录配置变更的标准化日志
    
    Args:
        config_key: 配置键
        old_value: 旧值
        new_value: 新值
    """
    logger.info(f"配置变更 - {config_key}: {old_value} → {new_value}")


def log_fallback(original_mode: str, fallback_mode: str, reason: str):
    """
    记录模式回退的标准化日志
    
    Args:
        original_mode: 原始模式
        fallback_mode: 回退模式
        reason: 回退原因
    """
    logger.warning(
        LogFormatter.format_warning(
            f"从 {original_mode} 回退到 {fallback_mode}",
            f"原因: {reason}"
        )
    )
