"""Configuration file loader for unified_logger."""

import json
from pathlib import Path
from typing import Any

from .core.exceptions import ConfigurationError


def load_config(config_path: str | Path) -> dict[str, Any]:
    """Load configuration from a JSON file.
    
    Args:
        config_path: Path to the JSON configuration file
        
    Returns:
        Dictionary containing the configuration
        
    Raises:
        ConfigurationError: If the file cannot be read or parsed
    """
    try:
        path = Path(config_path)
        if not path.exists():
            raise ConfigurationError(
                f"Configuration file not found: {config_path}",
                config_path=str(config_path)
            )
        
        with open(path, 'r', encoding='utf-8') as f:
            config = json.load(f)
        
        return config
    
    except json.JSONDecodeError as e:
        raise ConfigurationError(
            f"Invalid JSON in configuration file: {e}",
            config_path=str(config_path),
            details={"error": str(e)}
        )
    except Exception as e:
        raise ConfigurationError(
            f"Failed to load configuration file: {e}",
            config_path=str(config_path),
            details={"error": str(e)}
        )


def get_backend_config(config: dict[str, Any], backend_name: str) -> dict[str, Any]:
    """Extract backend configuration from full config.
    
    Args:
        config: Full configuration dictionary
        backend_name: Name of the backend (e.g., 'console', 'file', 'elasticsearch')
        
    Returns:
        Backend-specific configuration dictionary
        
    Raises:
        ConfigurationError: If backend configuration is not found
    """
    backends = config.get('backends', {})
    
    if backend_name not in backends:
        raise ConfigurationError(
            f"Backend '{backend_name}' not found in configuration",
            details={"available_backends": list(backends.keys())}
        )
    
    return backends[backend_name]


def get_logger_config(config: dict[str, Any]) -> dict[str, Any]:
    """Extract logger configuration from full config.
    
    Args:
        config: Full configuration dictionary
        
    Returns:
        Logger-specific configuration dictionary
    """
    return config.get('logger', {})
