from __future__ import annotations

from typing import List

from analogai.foundation.common.logging.app_logger import app_logger
from analogai.foundation.infrastructure.embeddings.http_client import post_json
from analogai.foundation.settings import config


class OpenAIEmbeddingProvider:
    def __init__(self, api_key: str | None = None, model_name: str | None = None):
        resolved_api_key = api_key or (config.get("OPENAI_API_KEY", "") or "")
        resolved_model_name = model_name or (config.get("embed.model", "") or "")
        if not resolved_api_key:
            raise ValueError("OPENAI_API_KEY is required for OpenAI embeddings")
        if not resolved_model_name:
            raise ValueError("EMBEDDING_MODEL_NAME is required for OpenAI embeddings")
        self._api_key = resolved_api_key
        self._model_name = resolved_model_name
        self._dimension: int | None = None

    @property
    def dimension(self) -> int | None:
        return self._dimension

    def encode(self, text: str) -> List[float]:
        if not text or not text.strip():
            if self._dimension is None:
                return []
            return [0.0] * self._dimension
        payload = {"model": self._model_name, "input": text}
        response = post_json(
            "https://api.openai.com/v1/embeddings",
            payload,
            headers={
                "Authorization": f"Bearer {self._api_key}",
                "Content-Type": "application/json",
            },
        )
        embedding = (response.get("data") or [{}])[0].get("embedding") or []
        if embedding and self._dimension is None:
            self._dimension = len(embedding)
        if not embedding:
            app_logger.warning("OpenAI embeddings returned empty vector")
        return embedding

    def encode_batch(self, texts: List[str]) -> List[List[float]]:
        if not texts:
            return []
        payload = {"model": self._model_name, "input": texts}
        response = post_json(
            "https://api.openai.com/v1/embeddings",
            payload,
            headers={
                "Authorization": f"Bearer {self._api_key}",
                "Content-Type": "application/json",
            },
        )
        data = response.get("data") or []
        embeddings = [item.get("embedding") or [] for item in data]
        if embeddings and self._dimension is None and embeddings[0]:
            self._dimension = len(embeddings[0])
        return embeddings
