"""Tests for embedder convenience layer."""

import json

import httpx
import pytest

from goodmem.registries.convenience import apply_convenience_transforms
from tests.conftest import EMBEDDER_RESPONSE


def _apply(kwargs):
    apply_convenience_transforms(("embedders", "create"), kwargs)
    return kwargs


def test_known_model_auto_fills_provider_type():
    kwargs = {"model_identifier": "text-embedding-3-small", "display_name": "Test"}
    result = _apply(kwargs)
    assert result["provider_type"] == "OPENAI"


def test_known_model_auto_fills_dimensionality():
    kwargs = {"model_identifier": "text-embedding-3-small", "display_name": "Test"}
    result = _apply(kwargs)
    assert result["dimensionality"] == 1536


def test_known_model_auto_fills_endpoint_url():
    kwargs = {"model_identifier": "text-embedding-3-small", "display_name": "Test"}
    result = _apply(kwargs)
    assert result["endpoint_url"] == "https://api.openai.com/v1"


def test_known_model_auto_fills_distribution_type():
    kwargs = {"model_identifier": "text-embedding-3-small", "display_name": "Test"}
    result = _apply(kwargs)
    assert result["distribution_type"] == "DENSE"


def test_explicit_values_win_over_registry():
    kwargs = {
        "model_identifier": "text-embedding-3-small",
        "display_name": "Test",
        "provider_type": "CUSTOM",
        "dimensionality": 768,
        "endpoint_url": "https://custom.example.com",
    }
    result = _apply(kwargs)
    assert result["provider_type"] == "CUSTOM"
    assert result["dimensionality"] == 768
    assert result["endpoint_url"] == "https://custom.example.com"


def test_api_key_converted_to_credentials():
    kwargs = {
        "model_identifier": "text-embedding-3-small",
        "display_name": "Test",
        "api_key": "sk-secret",
    }
    result = _apply(kwargs)
    assert "api_key" not in result
    assert result["credentials"]["kind"] == "CREDENTIAL_KIND_API_KEY"
    assert result["credentials"]["api_key"]["inline_secret"] == "sk-secret"


def test_api_key_and_credentials_raises():
    kwargs = {
        "display_name": "Test",
        "api_key": "sk-secret",
        "credentials": {"kind": "CUSTOM", "data": "custom"},
    }
    with pytest.raises(ValueError, match="Cannot specify both"):
        _apply(kwargs)


def test_unknown_model_no_auto_fill():
    kwargs = {"model_identifier": "unknown-model", "display_name": "Test"}
    result = _apply(kwargs)
    assert "provider_type" not in result
    assert "dimensionality" not in result
    # distribution_type still gets default
    assert result["distribution_type"] == "DENSE"


def test_create_round_trip(mock_client_factory):
    """Full round-trip: create embedder with known model, check request body."""
    captured = {}

    def handler(request: httpx.Request) -> httpx.Response:
        captured["body"] = json.loads(request.content)
        captured["headers"] = dict(request.headers)
        return httpx.Response(200, json=EMBEDDER_RESPONSE)

    client = mock_client_factory(handler)
    result = client.embedders.create(
        display_name="My Embedder",
        model_identifier="text-embedding-3-small",
        api_key="sk-test",
    )

    body = captured["body"]
    assert body["providerType"] == "OPENAI"
    assert body["dimensionality"] == 1536
    assert body["distributionType"] == "DENSE"
    assert "endpointUrl" in body
    assert result.embedder_id == "emb-123"


def test_auth_header_sent(mock_client_factory):
    """Verify the auth header is included in the request."""
    captured = {}

    def handler(request: httpx.Request) -> httpx.Response:
        captured["headers"] = dict(request.headers)
        return httpx.Response(200, json=EMBEDDER_RESPONSE)

    client = mock_client_factory(handler, api_key="gm_test_key")
    client.embedders.create(
        display_name="Test",
        model_identifier="text-embedding-3-small",
        api_key="sk-test",
    )

    assert captured["headers"]["x-api-key"] == "gm_test_key"
