"""Tests for JinaEmbedder — mocked HTTP."""

import pytest
import httpx
from pytest_httpx import HTTPXMock

from neo_cortex.embedder import JinaEmbedder


FAKE_EMBEDDING = [0.1] * 1024


@pytest.fixture
def embedder():
    return JinaEmbedder(api_key="test-key")


class TestJinaEmbedder:
    @pytest.mark.asyncio
    async def test_embed_passage_returns_embedding(self, embedder, httpx_mock: HTTPXMock):
        httpx_mock.add_response(json={"data": [{"embedding": FAKE_EMBEDDING}]})
        result = await embedder.embed_passage("some text")
        assert result == FAKE_EMBEDDING
        assert len(result) == 1024

    @pytest.mark.asyncio
    async def test_embed_query_returns_embedding(self, embedder, httpx_mock: HTTPXMock):
        httpx_mock.add_response(json={"data": [{"embedding": FAKE_EMBEDDING}]})
        result = await embedder.embed_query("search query")
        assert result == FAKE_EMBEDDING

    @pytest.mark.asyncio
    async def test_embed_passage_sends_correct_task(self, embedder, httpx_mock: HTTPXMock):
        httpx_mock.add_response(json={"data": [{"embedding": FAKE_EMBEDDING}]})
        await embedder.embed_passage("store this")
        request = httpx_mock.get_requests()[0]
        body = request.extensions.get("json") if hasattr(request, "extensions") else None
        # Parse from content if extensions not available
        import json
        body = json.loads(request.content)
        assert body["task"] == "retrieval.passage"
        assert body["dimensions"] == 1024

    @pytest.mark.asyncio
    async def test_embed_query_sends_correct_task(self, embedder, httpx_mock: HTTPXMock):
        httpx_mock.add_response(json={"data": [{"embedding": FAKE_EMBEDDING}]})
        await embedder.embed_query("find this")
        import json
        body = json.loads(httpx_mock.get_requests()[0].content)
        assert body["task"] == "retrieval.query"

    @pytest.mark.asyncio
    async def test_sends_auth_header(self, embedder, httpx_mock: HTTPXMock):
        httpx_mock.add_response(json={"data": [{"embedding": FAKE_EMBEDDING}]})
        await embedder.embed_passage("test")
        request = httpx_mock.get_requests()[0]
        assert request.headers["authorization"] == "Bearer test-key"

    @pytest.mark.asyncio
    async def test_http_error_raises(self, embedder, httpx_mock: HTTPXMock):
        httpx_mock.add_response(status_code=500)
        with pytest.raises(httpx.HTTPStatusError):
            await embedder.embed_passage("fail")
