"""Tests for LLM convenience layer and CreateLLMResponse envelope unwrapping."""

import json

import httpx
import pytest

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


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


def test_known_model_auto_fills_provider_type():
    kwargs = {"model_identifier": "gpt-4o", "display_name": "Test"}
    result = _apply(kwargs)
    assert result["provider_type"] == "OPENAI"


def test_known_model_auto_fills_max_context_length():
    kwargs = {"model_identifier": "gpt-4o", "display_name": "Test"}
    result = _apply(kwargs)
    assert result["max_context_length"] > 0


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


def test_explicit_values_win_over_registry():
    kwargs = {
        "model_identifier": "gpt-4o",
        "display_name": "Test",
        "provider_type": "VLLM",
        "endpoint_url": "http://localhost:8000",
    }
    result = _apply(kwargs)
    assert result["provider_type"] == "VLLM"
    assert result["endpoint_url"] == "http://localhost:8000"


def test_vllm_provider_no_auto_endpoint():
    """VLLM has None in endpoint map — user must provide endpoint_url."""
    kwargs = {
        "model_identifier": "unknown",
        "display_name": "Test",
        "provider_type": "VLLM",
    }
    result = _apply(kwargs)
    assert "endpoint_url" not in result


def test_api_key_converted_to_credentials():
    kwargs = {"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_create_unwraps_envelope(mock_client_factory):
    """LLM create should unwrap the CreateLLMResponse envelope."""
    envelope = {"llm": LLM_RESPONSE}

    def handler(request: httpx.Request) -> httpx.Response:
        return httpx.Response(200, json=envelope)

    client = mock_client_factory(handler)
    result = client.llms.create(
        display_name="GPT-4o",
        model_identifier="gpt-4o",
        api_key="sk-test",
    )

    # Should return LLMResponse directly, not CreateLLMResponse
    assert result.llm_id == "llm-123"
    assert result.display_name == "Test LLM"


def test_create_sends_correct_body(mock_client_factory):
    """Verify the request body contains auto-inferred fields."""
    captured = {}

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

    client = mock_client_factory(handler)
    client.llms.create(
        display_name="GPT-4o",
        model_identifier="gpt-4o",
        api_key="sk-test",
    )

    body = captured["body"]
    assert body["providerType"] == "OPENAI"
    assert "endpointUrl" in body
    assert "maxContextLength" in body
