"""Opening registry — add new opening modules to _OPENING_MODULES."""

from __future__ import annotations

from chess_cli.openings.models import Opening

_OPENING_MODULES = [
    "chess_cli.openings.london_system",
]

_registry: list[Opening] | None = None


def get_all_openings() -> list[Opening]:
    """Return all registered openings. Lazy-loaded on first call."""
    global _registry
    if _registry is not None:
        return _registry

    import importlib

    from chess_cli.openings.models import validate_opening

    _registry = []
    for module_name in _OPENING_MODULES:
        mod = importlib.import_module(module_name)
        opening = mod.OPENING
        if not validate_opening(opening):
            raise ValueError(f"Opening '{opening.name}' has invalid moves")
        _registry.append(opening)
    return _registry


def get_opening_by_slug(slug: str) -> Opening | None:
    """Find an opening by its slug."""
    for opening in get_all_openings():
        if opening.slug == slug:
            return opening
    return None
