"""
Loads and validates configuration from config.json.
Provides a centralized access point to configuration settings.
"""
import json
import os
from typing import Dict, Any

_config = None

def load_config() -> Dict[str, Any]:
    """
    Load, validate, and return the configuration from config.json.
    
    Returns:
        Configuration dictionary.
    
    Raises:
        FileNotFoundError: If config.json is not found.
        ValueError: If config.json is invalid or missing required keys.
    """
    global _config
    if _config is not None:
        return _config

    config_path = os.path.join(os.path.dirname(__file__), '..', '..', 'config.json')
    
    if not os.path.exists(config_path):
        raise FileNotFoundError(
            "config.json not found. Please create it based on config.example.json"
        )
    
    try:
        with open(config_path, 'r', encoding='utf-8') as f:
            config_data = json.load(f)
    except json.JSONDecodeError as e:
        raise ValueError(f"Invalid JSON in config.json: {e}")

    # --- Validation ---
    if 'vultr' not in config_data or 'api_key' not in config_data['vultr']:
        raise ValueError("Config validation failed: missing ['vultr']['api_key']")
    
    if 'billing_databases' not in config_data:
        # It's optional, so we can create an empty dict
        config_data['billing_databases'] = {}
        
    # --- Set global config ---
    _config = config_data
    return _config

def get_config() -> Dict[str, Any]:
    """
    Convenience function to get the loaded configuration.
    
    Returns:
        Configuration dictionary.
    """
    return load_config()
