"""LLMs API namespace — domain-specific logic on top of the generated base."""

from __future__ import annotations

from typing import Any

from goodmem._generated.api.llms_base import AsyncLlmsAPIBase, LlmsAPIBase
from goodmem._generated.models.create_llm_response import CreateLLMResponse
from goodmem._generated.models.llm_response import LLMResponse
from goodmem.registries.convenience import apply_convenience_transforms


def _unwrap_create_llm_response(value: LLMResponse | CreateLLMResponse) -> LLMResponse:
    """Return the inner LLMResponse for create()."""
    if isinstance(value, LLMResponse):
        return value
    return value.llm


class LlmsAPI(LlmsAPIBase):
    """LLMs API with GoodMem convenience defaults.

    Extends ``LlmsAPIBase`` with:

    - **Model registry**: auto-infers ``provider_type``, ``endpoint_url``, ``max_context_length``,
      and ``supported_modalities`` from ``model_identifier`` for 34 known models.
    - **api_key shorthand**: ``api_key="sk-..."`` converts to the full ``credentials`` structure.
    - **Endpoint URL inference**: ``endpoint_url`` is inferred from ``provider_type`` when not set.
    """

    def create(self, **kwargs: Any) -> LLMResponse:
        apply_convenience_transforms(("llms", "create"), kwargs)
        created = super().create(**kwargs)
        return _unwrap_create_llm_response(created)


class AsyncLlmsAPI(AsyncLlmsAPIBase):
    """Async LLMs API with GoodMem convenience defaults. See ``LlmsAPI``."""

    async def create(self, **kwargs: Any) -> LLMResponse:
        apply_convenience_transforms(("llms", "create"), kwargs)
        created = await super().create(**kwargs)
        return _unwrap_create_llm_response(created)
