"""
Serviço de embeddings para busca semântica
"""
import aiohttp
import asyncio
from typing import List

from config.settings import EmbeddingConfig


class EmbeddingService:
    """
    Serviço para gerar embeddings de textos
    Suporta: OpenAI embeddings, or local alternatives
    """

    def __init__(self, config: EmbeddingConfig):
        self.config = config
        self._cache = {}  # Simple cache

    async def get_embedding(self, text: str) -> List[float]:
        """
        Gera embedding para um texto
        Uses OpenAI's embedding API by default
        """
        # Check cache
        cache_key = hash(text)
        if cache_key in self._cache:
            return self._cache[cache_key]

        # Truncate if too long (approximate)
        max_chars = self.config.chunk_size * 4
        if len(text) > max_chars:
            text = text[:max_chars]

        try:
            embedding = await self._openai_embedding(text)
        except Exception:
            # Fallback: simple random embedding (for testing)
            import random
            embedding = [random.random() for _ in range(self.config.dimension)]

        self._cache[cache_key] = embedding
        return embedding

    async def _openai_embedding(self, text: str) -> List[float]:
        """Call OpenAI embedding API"""
        import os

        api_key = os.getenv("OPENAI_API_KEY")
        if not api_key:
            raise ValueError("OPENAI_API_KEY not set")

        async with aiohttp.ClientSession() as session:
            async with session.post(
                "https://api.openai.com/v1/embeddings",
                headers={
                    "Authorization": f"Bearer {api_key}",
                    "Content-Type": "application/json"
                },
                json={
                    "input": text,
                    "model": self.config.model
                }
            ) as response:
                if response.status != 200:
                    error = await response.text()
                    raise Exception(f"Embedding API error: {error}")

                data = await response.json()
                return data["data"][0]["embedding"]

    async def get_embeddings_batch(self, texts: List[str]) -> List[List[float]]:
        """Generate embeddings for multiple texts"""
        tasks = [self.get_embedding(text) for text in texts]
        return await asyncio.gather(*tasks)