"""
Configuration loading utility for MCP Guardian.

This module provides functionality to load and parse YAML configuration files
for the Guardian security middleware.
"""

import yaml
from typing import Dict, Any
from pathlib import Path


def load_config(path: str) -> Dict[str, Any]:
    """
    Load configuration from a YAML file.
    
    Args:
        path: Path to the YAML configuration file
        
    Returns:
        Dictionary containing the configuration data
        
    Raises:
        FileNotFoundError: If the configuration file doesn't exist
        yaml.YAMLError: If the YAML file is malformed
        ValueError: If required configuration sections are missing
    """
    config_path = Path(path)
    
    if not config_path.exists():
        raise FileNotFoundError(f"Configuration file not found: {path}")
    
    try:
        with open(config_path, 'r', encoding='utf-8') as file:
            config = yaml.safe_load(file)
    except yaml.YAMLError as e:
        raise yaml.YAMLError(f"Invalid YAML in configuration file: {e}")
    
    if not isinstance(config, dict):
        raise ValueError("Configuration file must contain a valid YAML dictionary")
    
    # Validate required sections
    required_sections = ['jwt', 'rate_limit']
    for section in required_sections:
        if section not in config:
            raise ValueError(f"Missing required configuration section: {section}")
    
    # Validate JWT configuration
    jwt_config = config['jwt']
    required_jwt_fields = ['public_key', 'algorithm', 'audience']
    for field in required_jwt_fields:
        if field not in jwt_config:
            raise ValueError(f"Missing required JWT configuration field: {field}")
    
    # Validate rate limit configuration
    rate_limit_config = config['rate_limit']
    required_rate_limit_fields = ['requests', 'period_minutes']
    for field in required_rate_limit_fields:
        if field not in rate_limit_config:
            raise ValueError(f"Missing required rate limit configuration field: {field}")
    
    return config
