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


class AzureFoundryEmbeddingProvider:
    """Azure AI Foundry embeddings via OpenAI-compatible endpoint."""

    def __init__(self, endpoint: str, api_key: str, deployment_name: str, api_version: str = "2024-02-15-preview"):
        if not endpoint:
            raise ValueError("AZURE_AI_FOUNDRY_ENDPOINT is required for Azure Foundry embeddings")
        if not api_key:
            raise ValueError("AZURE_AI_FOUNDRY_API_KEY is required for Azure Foundry embeddings")
        if not deployment_name:
            raise ValueError("EMBEDDING_MODEL_NAME (deployment) is required for Azure Foundry embeddings")
        self._endpoint = endpoint.rstrip("/")
        self._api_key = api_key
        self._deployment_name = deployment_name
        self._api_version = api_version
        self._dimension: int | None = None

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

    def _build_url(self) -> str:
        return (
            f"{self._endpoint}/openai/deployments/{self._deployment_name}/embeddings"
            f"?api-version={self._api_version}"
        )

    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
        response = post_json(
            self._build_url(),
            {"input": text},
            headers={"api-key": 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("Azure Foundry embeddings returned empty vector")
        return embedding

    def encode_batch(self, texts: List[str]) -> List[List[float]]:
        if not texts:
            return []
        response = post_json(
            self._build_url(),
            {"input": texts},
            headers={"api-key": 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
