import logging

from openai import OpenAI, AsyncOpenAI

from config import OPENAI_API_KEY

logger = logging.getLogger(__name__)

__all__ = ["create_embedding", "create_embedding_async", "get_embedding_client", "get_async_embedding_client"]


class EmbeddingClientManager:
    """
    Singleton Class quản lý OpenAI Embedding Client (Sync & Async).
    """

    def __init__(self):
        self._client: OpenAI | None = None
        self._async_client: AsyncOpenAI | None = None

    def get_client(self) -> OpenAI:
        """Sync Client lazy loading"""
        if self._client is None:
            if not OPENAI_API_KEY:
                raise RuntimeError("CRITICAL: OPENAI_API_KEY chưa được thiết lập")
            self._client = OpenAI(api_key=OPENAI_API_KEY)
        return self._client

    def get_async_client(self) -> AsyncOpenAI:
        """Async Client lazy loading"""
        if self._async_client is None:
            if not OPENAI_API_KEY:
                raise RuntimeError("CRITICAL: OPENAI_API_KEY chưa được thiết lập")
            self._async_client = AsyncOpenAI(api_key=OPENAI_API_KEY)
        return self._async_client


# --- Singleton ---
_manager = EmbeddingClientManager()
get_embedding_client = _manager.get_client
get_async_embedding_client = _manager.get_async_client


def create_embedding(text: str) -> list[float]:
    """Sync embedding generation"""
    try:
        client = get_embedding_client()
        response = client.embeddings.create(model="text-embedding-3-small", input=text)
        return response.data[0].embedding
    except Exception as e:
        logger.error(f"Error creating embedding (sync): {e}")
        return []


async def create_embedding_async(text: str) -> list[float]:
    """Async embedding generation"""
    try:
        client = get_async_embedding_client()
        response = await client.embeddings.create(model="text-embedding-3-small", input=text)
        return response.data[0].embedding
    except Exception as e:
        logger.error(f"Error creating embedding (async): {e}")
        return []
