"""Provider registry — discovery and registration of LLM providers."""

from __future__ import annotations

from orxaq.orchestration.providers.base import LLMProvider


class ProviderRegistry:
    """Central registry for LLM providers.

    Supports registration, lookup by name, and batch health-check.
    """

    def __init__(self) -> None:
        self._providers: dict[str, LLMProvider] = {}

    def register(self, provider: LLMProvider) -> None:
        """Register a provider instance."""
        self._providers[provider.name] = provider

    def get(self, name: str) -> LLMProvider | None:
        """Get provider by name."""
        return self._providers.get(name)

    def list_providers(self) -> list[str]:
        """Return sorted list of registered provider names."""
        return sorted(self._providers.keys())

    def all_providers(self) -> list[LLMProvider]:
        """Return all registered provider instances."""
        return list(self._providers.values())

    def health_check_all(self) -> dict[str, dict]:
        """Run health check on all registered providers."""
        results: dict[str, dict] = {}
        for name, provider in sorted(self._providers.items()):
            results[name] = provider.health_check()
        return results

    def available_models(self) -> dict[str, list[str]]:
        """Return models grouped by provider name."""
        result: dict[str, list[str]] = {}
        for name, provider in sorted(self._providers.items()):
            result[name] = provider.available_models()
        return result

    def remove(self, name: str) -> bool:
        """Remove a provider. Returns True if it existed."""
        return self._providers.pop(name, None) is not None

    def __len__(self) -> int:
        return len(self._providers)

    def __contains__(self, name: str) -> bool:
        return name in self._providers

    @classmethod
    def default(cls) -> ProviderRegistry:
        """Build registry with all known providers (auto-configured from env)."""
        registry = cls()

        from orxaq.orchestration.providers.anthropic import AnthropicProvider
        from orxaq.orchestration.providers.openai import OpenAIProvider
        from orxaq.orchestration.providers.vllm import VLLMProvider

        registry.register(VLLMProvider())
        registry.register(AnthropicProvider())
        registry.register(OpenAIProvider())

        return registry
