# src/utils.py
"""
工具函数模块 - 提供各种辅助功能
"""

import os
import logging
from pathlib import Path
from typing import Dict, Any, List, Optional
import yaml

logger = logging.getLogger(__name__)


def load_config(config_path: str = None) -> Dict[str, Any]:
    """
    加载配置文件
    
    Args:
        config_path: 配置文件路径，如果为None则使用默认路径
        
    Returns:
        配置字典
    """
    if config_path is None:
        config_path = os.path.join(os.path.dirname(__file__), '..', 'config.yaml')
    
    if not os.path.exists(config_path):
        logger.warning(f"配置文件不存在: {config_path}")
        return {}
    
    try:
        with open(config_path, 'r', encoding='utf-8') as f:
            config = yaml.safe_load(f)
        logger.info(f"成功加载配置文件: {config_path}")
        return config or {}
    except Exception as e:
        logger.error(f"加载配置文件失败: {e}")
        return {}


def setup_logging(config: Dict[str, Any]) -> None:
    """
    配置日志系统
    
    Args:
        config: 配置字典
    """
    logging_config = config.get('logging', {})
    level = logging_config.get('level', 'INFO')
    log_format = logging_config.get('format', '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    log_file = logging_config.get('file', None)
    
    # 创建logger
    logging.basicConfig(
        level=getattr(logging, level),
        format=log_format,
        handlers=[
            logging.StreamHandler(),
            logging.FileHandler(log_file) if log_file else logging.NullHandler()
        ]
    )


def validate_file_path(file_path: str, allowed_extensions: List[str] = None) -> bool:
    """
    验证文件路径的合法性
    
    Args:
        file_path: 文件路径
        allowed_extensions: 允许的文件扩展名列表（如['.pdf', '.docx']）
        
    Returns:
        文件是否合法
    """
    if not os.path.exists(file_path):
        logger.error(f"文件不存在: {file_path}")
        return False
    
    if not os.path.isfile(file_path):
        logger.error(f"路径不是文件: {file_path}")
        return False
    
    if allowed_extensions:
        ext = Path(file_path).suffix.lower()
        if ext not in allowed_extensions:
            logger.error(f"不支持的文件格式: {ext}")
            return False
    
    return True


def ensure_directory_exists(directory: str) -> bool:
    """
    确保目录存在，如果不存在则创建
    
    Args:
        directory: 目录路径
        
    Returns:
        目录是否存在或创建成功
    """
    try:
        Path(directory).mkdir(parents=True, exist_ok=True)
        return True
    except Exception as e:
        logger.error(f"创建目录失败: {e}")
        return False


def get_env_or_config(env_var: str, config_dict: Dict[str, Any], 
                      default: Any = None) -> Any:
    """
    优先从环境变量读取，其次从配置字典读取
    
    Args:
        env_var: 环境变量名
        config_dict: 配置字典
        default: 默认值
        
    Returns:
        获取到的值
    """
    # 尝试从环境变量读取
    env_value = os.environ.get(env_var)
    if env_value:
        return env_value
    
    # 尝试从配置字典读取
    config_value = config_dict.get(env_var)
    if config_value and not config_value.startswith('${'):
        return config_value
    
    return default
