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


def load_service_config(config_path: Optional[str] = None) -> Dict[str, Any]:
    """
    Load service configuration from modular YAML files.

    Loads:
    - config/app.yaml - Global app settings, auth, and shared config
    - config/services/*.yaml - Individual service configurations

    Returns a merged configuration dictionary.
    """
    if config_path is None:
        base_config_dir = Path(__file__).parent.parent.parent.parent / "config"

        # Load global app configuration
        app_config_path = base_config_dir / "app.yaml"
        with open(app_config_path, 'r', encoding='utf-8') as f:
            config = yaml.safe_load(f)

        # Initialize services dict if not present
        if "services" not in config:
            config["services"] = {}

        # Load individual service configurations
        services_dir = base_config_dir / "services"
        if services_dir.exists():
            for service_file in services_dir.glob("*.yaml"):
                service_name = service_file.stem  # filename without extension
                with open(service_file, 'r', encoding='utf-8') as f:
                    service_config = yaml.safe_load(f)
                    config["services"][service_name] = service_config

        return config
    else:
        # Support loading from custom path (for backward compatibility or testing)
        with open(config_path, 'r', encoding='utf-8') as f:
            config = yaml.safe_load(f)
        return config


def get_env_var(var_name: str, required: bool = True, default: Optional[str] = None) -> Optional[str]:
    """Get environment variable with validation"""
    value = os.getenv(var_name, default)
    if required and not value:
        raise ValueError(f"Required environment variable {var_name} is not set")
    return value


def resolve_env_var_from_config(config: Dict[str, Any], env_key: str, required: bool = True, default: Optional[str] = None) -> Optional[str]:
    """
    Resolve environment variable from config that specifies the env var name

    Example:
        config = {"api_key_env": "OPENAI_API_KEY"}
        resolve_env_var_from_config(config, "api_key_env")
        # Returns the value of os.getenv("OPENAI_API_KEY")
    """
    env_var_name = config.get(env_key)
    if not env_var_name:
        if required:
            raise ValueError(f"Config key '{env_key}' not found")
        return default

    return get_env_var(env_var_name, required=required, default=default)
