"""
Configuration utilities for MCP Agent.
Handles environment variable substitution and config merging.
"""
import os
import re
from typing import Dict, Any


def substitute_env_vars(config: Dict[str, Any], env_vars: Dict[str, str] = None) -> Dict[str, Any]:
    """
    Recursively substitute environment variables in config values.
    
    Supports ${VAR_NAME} syntax for environment variable substitution.
    
    Args:
        config: Configuration dictionary
        env_vars: Optional dictionary of environment variables to use.
                 If None, uses os.environ.
    
    Returns:
        Config dictionary with substituted values
    """
    if env_vars is None:
        env_vars = dict(os.environ)
    
    def substitute_value(value):
        if isinstance(value, str):
            # Find all ${VAR_NAME} patterns
            pattern = r'\$\{([^}]+)\}'
            
            def replacer(match):
                var_name = match.group(1)
                # First check provided env_vars, then os.environ
                return env_vars.get(var_name, os.environ.get(var_name, match.group(0)))
            
            return re.sub(pattern, replacer, value)
        elif isinstance(value, dict):
            return {k: substitute_value(v) for k, v in value.items()}
        elif isinstance(value, list):
            return [substitute_value(item) for item in value]
        else:
            return value
    
    return substitute_value(config)


def merge_secrets_into_config(config: Dict[str, Any], secrets: Dict[str, Any]) -> Dict[str, Any]:
    """
    Merge secrets into config and handle environment variable substitution.
    
    This function:
    1. Creates a combined environment from secrets
    2. Substitutes variables in the config using these values
    
    Args:
        config: Main configuration dictionary
        secrets: Secrets dictionary
    
    Returns:
        Merged and substituted configuration
    """
    # Extract all top-level values from secrets as potential env vars
    env_vars = {}
    
    # Add all string values from secrets as potential env vars
    for key, value in secrets.items():
        if isinstance(value, str):
            env_vars[key.upper()] = value
        elif isinstance(value, dict):
            # For nested dicts like 'openai': {'api_key': 'xxx'}
            for sub_key, sub_value in value.items():
                if isinstance(sub_value, str):
                    # Create both formats: OPENAI_API_KEY and api_key
                    env_vars[f"{key.upper()}_{sub_key.upper()}"] = sub_value
                    env_vars[sub_key] = sub_value
    
    # Now substitute variables in config
    substituted_config = substitute_env_vars(config, env_vars)
    
    return substituted_config 