"""
Adapter registry for discovering and instantiating executor adapters.

This follows the same pattern as the watcher registry, enabling:
- Easy addition of new adapters without modifying orchestrator code
- Runtime discovery of available adapters
- Consistent instantiation across CLI and orchestrator
"""

from __future__ import annotations

from typing import Any, Type

from zwarm.adapters.base import ExecutorAdapter


# Global adapter registry
_ADAPTERS: dict[str, Type[ExecutorAdapter]] = {}


def register_adapter(name: str):
    """
    Decorator to register an adapter class.

    Example:
        @register_adapter("codex_mcp")
        class CodexMCPAdapter(ExecutorAdapter):
            ...
    """

    def decorator(cls: Type[ExecutorAdapter]) -> Type[ExecutorAdapter]:
        cls.name = name
        _ADAPTERS[name] = cls
        return cls

    return decorator


def get_adapter(name: str, model: str | None = None, **kwargs: Any) -> ExecutorAdapter:
    """
    Get an adapter instance by name.

    Args:
        name: Registered adapter name (e.g., "codex_mcp", "claude_code")
        model: Optional model override to pass to adapter
        **kwargs: Additional kwargs passed to adapter constructor

    Returns:
        Instantiated adapter

    Raises:
        ValueError: If adapter not found
    """
    if name not in _ADAPTERS:
        available = list(_ADAPTERS.keys())
        raise ValueError(
            f"Unknown adapter: {name}. Available: {available}"
        )
    return _ADAPTERS[name](model=model, **kwargs)


def list_adapters() -> list[str]:
    """List all registered adapter names."""
    return list(_ADAPTERS.keys())


def adapter_exists(name: str) -> bool:
    """Check if an adapter is registered."""
    return name in _ADAPTERS
