"""Tests for reranker convenience layer."""

import json

import httpx

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


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


def test_known_model_auto_fills_provider_type():
    kwargs = {"model_identifier": "rerank-v3.5", "display_name": "Test"}
    result = _apply(kwargs)
    assert result["provider_type"] == "COHERE"


def test_known_model_auto_fills_endpoint_url():
    kwargs = {"model_identifier": "rerank-v3.5", "display_name": "Test"}
    result = _apply(kwargs)
    assert result["endpoint_url"] == "https://api.cohere.com"


def test_jina_model_auto_fills():
    kwargs = {"model_identifier": "jina-reranker-v2-base-multilingual", "display_name": "Test"}
    result = _apply(kwargs)
    assert result["provider_type"] == "JINA"
    assert result["endpoint_url"] == "https://api.jina.ai"


def test_explicit_values_win_over_registry():
    kwargs = {
        "model_identifier": "rerank-v3.5",
        "display_name": "Test",
        "provider_type": "CUSTOM",
        "endpoint_url": "https://custom.example.com",
    }
    result = _apply(kwargs)
    assert result["provider_type"] == "CUSTOM"
    assert result["endpoint_url"] == "https://custom.example.com"


def test_api_key_converted_to_credentials():
    kwargs = {"display_name": "Test", "api_key": "key-123"}
    result = _apply(kwargs)
    assert "api_key" not in result
    assert result["credentials"]["kind"] == "CREDENTIAL_KIND_API_KEY"


def test_create_round_trip(mock_client_factory):
    captured = {}

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

    client = mock_client_factory(handler)
    result = client.rerankers.create(
        display_name="My Reranker",
        model_identifier="rerank-v3.5",
        api_key="key-test",
    )

    body = captured["body"]
    assert body["providerType"] == "COHERE"
    assert "endpointUrl" in body
    assert result.reranker_id == "rr-123"
