"""Embedders API namespace."""

from __future__ import annotations

from typing import Any

from goodmem._base import AsyncCRUDNamespace, CRUDNamespace
from goodmem._generated.models.embedder_creation_request import EmbedderCreationRequest
from goodmem._generated.models.embedder_response import EmbedderResponse
from goodmem._generated.models.list_embedders_response import ListEmbeddersResponse
from goodmem._generated.models.update_embedder_request import UpdateEmbedderRequest
from goodmem._registries import EMBEDDER_MODEL_REGISTRY
from goodmem._schema_bridge import DEFAULT_DISTRIBUTION_TYPE, build_api_key_credentials

_PROVIDER_ENDPOINT_MAP = {
    "OPENAI": "https://api.openai.com/v1",
    "COHERE": "https://api.cohere.com",
    "JINA": "https://api.jina.ai",
    "VOYAGE": "https://api.voyageai.com/v1",
}


def _apply_embedder_defaults(kwargs: dict[str, Any]) -> dict[str, Any]:
    """Apply model registry defaults and api_key convenience."""
    model_id = kwargs.get("model_identifier")
    if model_id and model_id in EMBEDDER_MODEL_REGISTRY:
        defaults = EMBEDDER_MODEL_REGISTRY[model_id]
        for key, value in defaults.items():
            kwargs.setdefault(key, value)
        # Auto-infer endpoint_url from provider_type
        pt = kwargs.get("provider_type")
        if pt and "endpoint_url" not in kwargs and pt in _PROVIDER_ENDPOINT_MAP:
            kwargs["endpoint_url"] = _PROVIDER_ENDPOINT_MAP[pt]

    # api_key convenience → credentials
    api_key = kwargs.pop("api_key", None)
    if api_key:
        kwargs.setdefault("credentials", build_api_key_credentials(api_key))

    # Default distribution_type
    kwargs.setdefault("distribution_type", DEFAULT_DISTRIBUTION_TYPE)

    return kwargs


class EmbeddersAPI(CRUDNamespace):
    _base_path = "/v1/embedders"
    _create_model = EmbedderCreationRequest
    _update_model = UpdateEmbedderRequest
    _response_model = EmbedderResponse
    _list_response_model = ListEmbeddersResponse
    _list_items_field = "embedders"

    def create(self, **kwargs: Any) -> EmbedderResponse:
        """Create an embedder. Model registry auto-infers provider_type, dimensionality, etc."""
        kwargs = _apply_embedder_defaults(kwargs)
        return super().create(**kwargs)


class AsyncEmbeddersAPI(AsyncCRUDNamespace):
    _base_path = "/v1/embedders"
    _create_model = EmbedderCreationRequest
    _update_model = UpdateEmbedderRequest
    _response_model = EmbedderResponse
    _list_response_model = ListEmbeddersResponse
    _list_items_field = "embedders"

    async def create(self, **kwargs: Any) -> EmbedderResponse:
        kwargs = _apply_embedder_defaults(kwargs)
        return await super().create(**kwargs)
