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

import logging
import os
import sys
import time

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"

# Direct file logging — survives C-level crashes (flushes every write)
_DATA_DIR = os.environ.get("CORTEX_DATA_DIR") or os.getcwd()
_LOG_DIR = os.path.join(_DATA_DIR, "cortex_db") if os.environ.get("CORTEX_DATA_DIR") else _DATA_DIR
_LOG_PATH = os.path.join(_LOG_DIR, "neo-cortex.log")


def _bl(msg: str) -> None:
    try:
        with open(_LOG_PATH, "a", encoding="utf-8") as f:
            f.write(f"{time.strftime('%Y-%m-%d %H:%M:%S')} [EMBED] {msg}\n")
            f.flush()
    except Exception:
        pass


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

    def __init__(self, api_key: str):
        self._api_key = api_key
        _bl(f"init: verify_ssl={_VERIFY_SSL}")
        self._client = httpx.AsyncClient(timeout=30.0, verify=_VERIFY_SSL)
        _bl("init: httpx.AsyncClient created OK")

    async def embed_passage(self, text: str) -> list[float]:
        """Embed text for storage (retrieval.passage task adapter)."""
        _bl(f"embed_passage: text_len={len(text)}")
        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)."""
        _bl(f"embed_query: text_len={len(text)}")
        return await self._embed(text, task="retrieval.query")

    async def _embed(self, text: str, task: str) -> list[float]:
        _bl(f"_embed: task={task}, url={config.JINA_URL}")
        _bl(f"_embed: building request body")
        body = {
            "model": config.JINA_MODEL,
            "task": task,
            "dimensions": config.JINA_DIMENSIONS,
            "input": [text],
        }
        headers = {
            "Authorization": f"Bearer {self._api_key[:8]}...",
            "Content-Type": "application/json",
        }
        _bl(f"_embed: calling httpx.post → {config.JINA_URL}")
        try:
            resp = await self._client.post(
                config.JINA_URL,
                headers={
                    "Authorization": f"Bearer {self._api_key}",
                    "Content-Type": "application/json",
                },
                json=body,
            )
            _bl(f"_embed: response status={resp.status_code}")
            resp.raise_for_status()
            data = resp.json()
            _bl(f"_embed: OK, embedding dim={len(data['data'][0]['embedding'])}")
            return data["data"][0]["embedding"]
        except Exception as e:
            _bl(f"_embed: FAILED: {type(e).__name__}: {e}")
            raise

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