"""Tests for embedding providers."""
import struct
from unittest.mock import patch, MagicMock

import pytest

from greymatter_core.embeddings import (
    OllamaEmbedding,
    serialize_f32,
    deserialize_f32,
)


def test_serialize_f32_roundtrip():
    """Serializing and deserializing a float vector should be lossless."""
    vec = [0.1, 0.2, 0.3, 0.4]
    blob = serialize_f32(vec)
    assert isinstance(blob, bytes)
    assert len(blob) == 4 * 4  # 4 floats * 4 bytes each
    result = deserialize_f32(blob)
    assert len(result) == 4
    for a, b in zip(vec, result):
        assert abs(a - b) < 1e-6


def test_serialize_f32_768_dimensions():
    """768-dimension vectors should serialize correctly."""
    vec = [float(i) / 768 for i in range(768)]
    blob = serialize_f32(vec)
    assert len(blob) == 768 * 4
    result = deserialize_f32(blob)
    assert len(result) == 768


@patch("greymatter_core.embeddings.httpx")
def test_ollama_embed_single(mock_httpx):
    """OllamaEmbedding.embed() should return a list of floats."""
    fake_vector = [0.1] * 768
    mock_response = MagicMock()
    mock_response.json.return_value = {"embeddings": [fake_vector]}
    mock_response.raise_for_status = MagicMock()
    mock_httpx.post.return_value = mock_response

    embedder = OllamaEmbedding()
    result = embedder.embed("test query")

    assert result == fake_vector
    assert len(result) == 768
    mock_httpx.post.assert_called_once()


@patch("greymatter_core.embeddings.httpx")
def test_ollama_embed_batch(mock_httpx):
    """OllamaEmbedding.embed_batch() should return multiple vectors."""
    fake_vectors = [[0.1] * 768, [0.2] * 768, [0.3] * 768]
    mock_response = MagicMock()
    mock_response.json.return_value = {"embeddings": fake_vectors}
    mock_response.raise_for_status = MagicMock()
    mock_httpx.post.return_value = mock_response

    embedder = OllamaEmbedding()
    result = embedder.embed_batch(["text1", "text2", "text3"])

    assert len(result) == 3
    assert all(len(v) == 768 for v in result)


def test_ollama_embedding_dimensions():
    """OllamaEmbedding should report 768 dimensions."""
    embedder = OllamaEmbedding()
    assert embedder.dimensions == 768
