"""Community adapter loader — scan data/game_adapters/ for YAML adapter files.

Loads all .yaml/.yml files from the community adapter directory and makes
them available for selection when creating game integrations.
"""

from pathlib import Path
from typing import Any

from wled_controller.core.game_integration.mapping_adapter import (
    MappingAdapter,
    load_adapter_from_yaml,
)
from wled_controller.utils import get_logger

logger = get_logger(__name__)

# Default directory for community adapter YAML files
_DEFAULT_ADAPTER_DIR = Path(__file__).parent.parent.parent / "data" / "game_adapters"

# Registry of loaded community adapters (adapter_type -> MappingAdapter instance)
_community_adapters: dict[str, MappingAdapter] = {}


def get_community_adapter_dir(custom_dir: str | Path | None = None) -> Path:
    """Return the community adapter directory path.

    Args:
        custom_dir: Optional override path. Falls back to built-in data/game_adapters/.

    Returns:
        Path to the adapter directory.
    """
    if custom_dir:
        return Path(custom_dir)
    return _DEFAULT_ADAPTER_DIR


def load_community_adapters(
    adapter_dir: str | Path | None = None,
) -> dict[str, MappingAdapter]:
    """Scan a directory for YAML adapter files and load them.

    Args:
        adapter_dir: Directory to scan. Defaults to data/game_adapters/.

    Returns:
        Dict mapping adapter type keys to MappingAdapter instances.
    """
    directory = get_community_adapter_dir(adapter_dir)

    if not directory.exists():
        logger.info("Community adapter directory not found: %s", directory)
        return {}

    loaded: dict[str, MappingAdapter] = {}
    yaml_files = sorted(directory.glob("*.yaml")) + sorted(directory.glob("*.yml"))

    for yaml_path in yaml_files:
        try:
            adapter = load_adapter_from_yaml(yaml_path)
            # Use filename stem as the adapter key
            adapter_key = f"community_{yaml_path.stem}"
            loaded[adapter_key] = adapter
            logger.info(
                "Loaded community adapter '%s' (%s) from %s",
                adapter.name,
                adapter.game,
                yaml_path.name,
            )
        except (ValueError, FileNotFoundError) as exc:
            logger.warning("Failed to load community adapter %s: %s", yaml_path.name, exc)

    return loaded


def register_community_adapters(
    adapter_dir: str | Path | None = None,
) -> int:
    """Load community adapters and store them in the module-level registry.

    Args:
        adapter_dir: Directory to scan. Defaults to data/game_adapters/.

    Returns:
        Number of adapters successfully loaded.
    """
    global _community_adapters
    _community_adapters = load_community_adapters(adapter_dir)
    count = len(_community_adapters)
    if count > 0:
        logger.info("Registered %d community adapter(s)", count)
    return count


def get_community_adapters() -> dict[str, MappingAdapter]:
    """Return all loaded community adapters.

    Returns:
        Dict mapping adapter keys to MappingAdapter instances.
    """
    return dict(_community_adapters)


def get_community_adapter(adapter_key: str) -> MappingAdapter | None:
    """Look up a community adapter by its key.

    Args:
        adapter_key: The adapter key (e.g. 'community_minecraft').

    Returns:
        The MappingAdapter instance, or None if not found.
    """
    return _community_adapters.get(adapter_key)


def get_community_adapter_info() -> list[dict[str, Any]]:
    """Return metadata for all loaded community adapters.

    Returns:
        List of dicts with adapter_type, display_name, game_name, supported_events.
    """
    result = []
    for adapter_key, adapter in _community_adapters.items():
        result.append(
            {
                "adapter_type": adapter_key,
                "display_name": adapter.name,
                "game_name": adapter.game,
                "supported_events": adapter.supported_events,
                "source": "community",
            }
        )
    return result


def clear_community_adapters() -> None:
    """Clear all loaded community adapters (for testing)."""
    global _community_adapters
    _community_adapters = {}
