from unittest.mock import MagicMock

import pytest

from spark_advisor_analyzer.ai.client import LlmClient


class TestLlmClient:
    def test_not_initialized_raises(self):
        client = LlmClient(base_url="https://openrouter.ai/api/v1", api_key="sk-test", timeout=30.0)
        with pytest.raises(RuntimeError, match="Client not initialized"):
            client.create_message(
                model="test", max_tokens=100, system="sys",
                messages=[], tools=None, tool_choice=None,
            )

    def test_open_creates_client(self):
        client = LlmClient(base_url="https://openrouter.ai/api/v1", api_key="sk-test", timeout=30.0)
        client.open()
        assert client._client is not None
        client.close()

    def test_context_manager(self):
        with LlmClient(base_url="https://openrouter.ai/api/v1", api_key="sk-test", timeout=30.0) as client:
            assert client._client is not None

    def test_create_message_calls_openai(self):
        client = LlmClient(base_url="https://openrouter.ai/api/v1", api_key="sk-test", timeout=30.0)
        client.open()
        client._client = MagicMock()
        mock_response = MagicMock()
        client._client.chat.completions.create.return_value = mock_response

        result = client.create_message(
            model="test-model",
            max_tokens=100,
            system="You are helpful",
            messages=[{"role": "user", "content": "hello"}],
            tools=[{"type": "function", "function": {"name": "t", "parameters": {}}}],
            tool_choice="auto",
        )

        assert result == mock_response
        call_kwargs = client._client.chat.completions.create.call_args.kwargs
        assert call_kwargs["model"] == "test-model"
        assert call_kwargs["messages"][0] == {"role": "system", "content": "You are helpful"}
        assert call_kwargs["messages"][1] == {"role": "user", "content": "hello"}
        assert "tools" in call_kwargs
        client.close()
