"""Tests for OpenAICompatibleClient."""
import pytest
from unittest.mock import AsyncMock, MagicMock
from neo_cortex.llm import OpenAICompatibleClient, LLMClient


class TestOpenAICompatibleClient:
    def test_implements_llm_client(self):
        client = OpenAICompatibleClient("http://localhost:11434/v1", "test-key", "llama3.2")
        assert isinstance(client, LLMClient)

    def test_name_property(self):
        client = OpenAICompatibleClient("http://localhost:11434/v1", "test-key", "llama3.2")
        assert client.name == "openai-compatible/llama3.2"

    @pytest.mark.asyncio
    async def test_call_sends_correct_payload(self):
        client = OpenAICompatibleClient("http://localhost:11434/v1", "test-key", "llama3.2")
        mock_response = MagicMock()
        mock_response.json.return_value = {
            "choices": [{"message": {"content": "result"}}]
        }
        mock_response.raise_for_status = MagicMock()
        client._client = AsyncMock()
        client._client.post = AsyncMock(return_value=mock_response)

        result = await client.call("system prompt", "user text", max_tokens=500)
        assert result == "result"

        call_args = client._client.post.call_args
        assert "/v1/chat/completions" in call_args[0][0]
        payload = call_args[1]["json"]
        assert payload["model"] == "llama3.2"
        assert len(payload["messages"]) == 2  # system + user

    @pytest.mark.asyncio
    async def test_call_without_api_key(self):
        """Ollama doesn't need API key — should work with empty string."""
        client = OpenAICompatibleClient("http://localhost:11434/v1", "", "llama3.2")
        mock_response = MagicMock()
        mock_response.json.return_value = {
            "choices": [{"message": {"content": "ok"}}]
        }
        mock_response.raise_for_status = MagicMock()
        client._client = AsyncMock()
        client._client.post = AsyncMock(return_value=mock_response)

        result = await client.call("prompt", "text")
        assert result == "ok"

    @pytest.mark.asyncio
    async def test_close(self):
        client = OpenAICompatibleClient("http://localhost:11434/v1", "", "llama3.2")
        client._client = AsyncMock()
        await client.close()
        client._client.aclose.assert_called_once()
