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

CONFIG_PATH = "crumbforest_config.json"

class ConfigLoader:
    _config: Optional[Dict[str, Any]] = None

    @classmethod
    def load_config(cls, force_reload: bool = False) -> Dict[str, Any]:
        if cls._config is None or force_reload:
            try:
                paths_to_try = [CONFIG_PATH, os.path.join("..", CONFIG_PATH), "/config/crumbforest_config.json"]
                found = False
                for path in paths_to_try:
                    if os.path.exists(path):
                        try:
                            with open(path, 'r', encoding='utf-8') as f:
                                cls._config = json.load(f)
                            found = True
                            print(f"Loaded config from {path}")
                            break
                        except Exception as e:
                            print(f"Failed to load config from {path}: {e}")
                            continue
                
                if not found:
                    print(f"Warning: {CONFIG_PATH} not found in {paths_to_try}")
                    cls._config = {"roles": {}, "groups": {}, "theme_variants": {}}
                    
            except Exception as e:
                print(f"Error loading config: {e}")
                cls._config = {"roles": {}, "groups": {}, "theme_variants": {}}
                
        return cls._config

    @classmethod
    def get_role(cls, role_id: str) -> Optional[Dict[str, Any]]:
        config = cls.load_config()
        return config.get('roles', {}).get(role_id)

    @classmethod
    def get_group(cls, group_id: str) -> Optional[Dict[str, Any]]:
        config = cls.load_config()
        return config.get('groups', {}).get(group_id)

    @classmethod
    def get_theme(cls, theme_id: str) -> Optional[Dict[str, Any]]:
        config = cls.load_config()
        return config.get('theme_variants', {}).get(theme_id)

    @classmethod
    def get_all_roles(cls) -> Dict[str, Any]:
        config = cls.load_config()
        return config.get('roles', {})
