"""Jina v3 embedder — async HTTP client for text embeddings."""

import logging
import sys

import httpx

from neo_cortex import config

logger = logging.getLogger(__name__)

# uv-managed Python on Windows has broken OpenSSL (ssl.create_default_context() crashes).
# Disable SSL verification on Windows to bypass the OPENSSL_Applink bug.
_VERIFY_SSL = sys.platform != "win32"


class JinaEmbedder:
    """Async Jina Embeddings v3 client. 1024 dimensions, task adapters."""

    def __init__(self, api_key: str):
        self._api_key = api_key
        self._client = httpx.AsyncClient(timeout=30.0, verify=_VERIFY_SSL)

    async def embed_passage(self, text: str) -> list[float]:
        """Embed text for storage (retrieval.passage task adapter)."""
        return await self._embed(text, task="retrieval.passage")

    async def embed_query(self, text: str) -> list[float]:
        """Embed text for search (retrieval.query task adapter)."""
        return await self._embed(text, task="retrieval.query")

    async def _embed(self, text: str, task: str) -> list[float]:
        resp = await self._client.post(
            config.JINA_URL,
            headers={
                "Authorization": f"Bearer {self._api_key}",
                "Content-Type": "application/json",
            },
            json={
                "model": config.JINA_MODEL,
                "task": task,
                "dimensions": config.JINA_DIMENSIONS,
                "input": [text],
            },
        )
        resp.raise_for_status()
        data = resp.json()
        return data["data"][0]["embedding"]

    async def close(self) -> None:
        await self._client.aclose()
