import os
import json
import inspect
from typing import Dict, Any


def load_configuration() -> Dict[str, Any]:
    """
    Load configuration from script_config.json in the current script directory.

    Returns:
        Dict containing configurations with levels 1, 2, 3 and working_directory

    Example usage in scripts:
        from script_utils import load_configuration

        configs = load_configuration()
        level1_config = configs.get("level1", {})
        level2_config = configs.get("level2", {})
        level3_config = configs.get("level3", {})
        working_dir = configs.get("working_directory", "")
    """
    try:
        # Obtener el frame del llamador
        caller_frame = inspect.stack()[1]
        caller_file = caller_frame.filename
        # Obtener el directorio del script que llama a esta función
        script_dir = os.path.dirname(os.path.abspath(caller_file))

        # Path to the config file
        config_file_path = os.path.join(script_dir, "script_config.json")

        # Check if file exists
        if not os.path.exists(config_file_path):
            print(f"Configuration file not found: {config_file_path}")
            return {}

        # Load and parse the JSON file
        with open(config_file_path, "r", encoding="utf-8") as f:
            return json.load(f)

    except json.JSONDecodeError as e:
        print(f"Error parsing configuration file: {str(e)}")
        return {}
    except Exception as e:
        print(f"Error loading configuration: {str(e)}")
        return {}
