"""
Demo Configs — Auto-Discovery Module

Scans this folder for Python files that contain subclasses of _BaseDemoConfig
and exposes them via _getAvailableDemoConfigs().
"""

import importlib
import inspect
import logging
import pkgutil
from typing import Dict

from modules.demoConfigs._baseDemoConfig import _BaseDemoConfig

logger = logging.getLogger(__name__)

_configCache: Dict[str, _BaseDemoConfig] = {}


def _getAvailableDemoConfigs() -> Dict[str, _BaseDemoConfig]:
    """Return a dict of code -> instance for every discovered demo config."""
    if _configCache:
        return _configCache

    package = __name__
    packagePath = __path__

    for importer, moduleName, isPkg in pkgutil.iter_modules(packagePath):
        if moduleName.startswith("_"):
            continue
        try:
            module = importlib.import_module(f"{package}.{moduleName}")
            for name, obj in inspect.getmembers(module, inspect.isclass):
                if issubclass(obj, _BaseDemoConfig) and obj is not _BaseDemoConfig:
                    instance = obj()
                    if instance.code:
                        _configCache[instance.code] = instance
                        logger.info(f"Discovered demo config: {instance.code} ({instance.label})")
        except Exception as e:
            logger.warning(f"Failed to load demo config module '{moduleName}': {e}")

    return _configCache


def _getDemoConfigByCode(code: str) -> _BaseDemoConfig | None:
    """Get a specific demo config by its code."""
    configs = _getAvailableDemoConfigs()
    return configs.get(code)
