"""Embedding generation via OpenAI text-embedding API."""

import logging

import httpx

from app.config import OPENAI_API_KEY, OPENAI_EMBED_MODEL, OPENAI_EMBED_DIM

log = logging.getLogger(__name__)


async def generate_embedding(text: str) -> list[float] | None:
    """Generate a vector embedding for the given text. Returns list of floats or None on failure."""
    if not OPENAI_API_KEY or not text.strip():
        return None

    # Truncate to ~8000 chars for embedding model token limit
    truncated = text[:8000]

    try:
        async with httpx.AsyncClient(timeout=20) as client:
            resp = await client.post(
                "https://api.openai.com/v1/embeddings",
                headers={"Authorization": f"Bearer {OPENAI_API_KEY}"},
                json={
                    "model": OPENAI_EMBED_MODEL,
                    "input": truncated,
                    "dimensions": OPENAI_EMBED_DIM,
                },
            )
            resp.raise_for_status()
            data = resp.json()
            return data["data"][0]["embedding"]
    except Exception as e:
        log.error(f"Embedding generation failed: {e}")
        return None
