"""Configured provider catalog."""

from __future__ import annotations

from dataclasses import dataclass
from typing import TYPE_CHECKING

from memnixa.config import AppConfig, ProviderConfig
from memnixa.i18n import t
from memnixa.providers.registry import get_provider_spec

if TYPE_CHECKING:
    from memnixa.providers.openai_compatible import OpenAICompatibleProvider


@dataclass(slots=True)
class ProviderManager:
    """Resolve configured providers by id."""

    config: AppConfig

    def list_profiles(self) -> list[ProviderConfig]:
        """Return all configured provider profiles."""
        return self.config.list_provider_configs()

    def get_profile(self, provider_id: str | None = None) -> ProviderConfig:
        """Resolve one configured provider profile."""
        if provider_id is None:
            return self.config.get_provider_config(None)
        for profile in self.list_profiles():
            if profile.id == str(provider_id):
                return profile
        available = ", ".join(profile.id for profile in self.list_profiles())
        raise ValueError(
            t(
                "agent.provider.unknown",
                provider_id=provider_id,
                available=available,
            )
        )

    def build(self, provider_id: str | None = None) -> OpenAICompatibleProvider:
        """Build a provider client for the given profile."""
        from memnixa.providers.openai_compatible import OpenAICompatibleProvider

        profile = self.get_profile(provider_id)
        spec = get_provider_spec(profile.preset)
        return OpenAICompatibleProvider(
            spec=spec,
            api_key=profile.api_key,
            api_base=profile.api_base or spec.default_base_url,
            _model_name=profile.model or spec.default_model,
            timeout=self.config.request_timeout,
        )

    def describe(self, provider_id: str | None = None) -> dict[str, str]:
        """Return a display-friendly description of a provider profile."""
        profile = self.get_profile(provider_id)
        spec = get_provider_spec(profile.preset)
        model_name = profile.model or spec.default_model
        label = profile.label or spec.label
        return {
            "id": profile.id,
            "preset": profile.preset,
            "label": label,
            "model": model_name,
        }
