"""Tests for Ollama provider (unit tests with mocked HTTP)."""

from unittest.mock import patch, MagicMock
from milco.llm.ollama import OllamaProvider


def test_ollama_name():
    p = OllamaProvider(model="llama3")
    assert p.name == "ollama"


def test_ollama_default_base_url():
    p = OllamaProvider(model="llama3")
    assert p.base_url == "http://localhost:11434"


def test_ollama_custom_base_url():
    p = OllamaProvider(model="llama3", base_url="http://myhost:1234")
    assert p.base_url == "http://myhost:1234"


def test_ollama_complete_calls_api():
    p = OllamaProvider(model="llama3")
    mock_response = MagicMock()
    mock_response.status_code = 200
    mock_response.json.return_value = {"response": "Hello back!"}
    mock_response.raise_for_status = MagicMock()

    with patch("milco.llm.ollama.httpx.post", return_value=mock_response) as mock_post:
        result = p.complete("Hello")

    assert result == "Hello back!"
    mock_post.assert_called_once()
    call_kwargs = mock_post.call_args
    body = call_kwargs.kwargs.get("json") or call_kwargs[1].get("json")
    assert body["model"] == "llama3"
    assert body["prompt"] == "Hello"


def test_ollama_complete_with_system_prompt():
    p = OllamaProvider(model="llama3")
    mock_response = MagicMock()
    mock_response.status_code = 200
    mock_response.json.return_value = {"response": "Sure!"}
    mock_response.raise_for_status = MagicMock()

    with patch("milco.llm.ollama.httpx.post", return_value=mock_response) as mock_post:
        p.complete("Do the thing", system="You are helpful")

    call_kwargs = mock_post.call_args
    body = call_kwargs.kwargs.get("json") or call_kwargs[1].get("json")
    assert body["system"] == "You are helpful"


def test_ollama_ping_success():
    p = OllamaProvider(model="llama3")
    mock_response = MagicMock()
    mock_response.status_code = 200

    with patch("milco.llm.ollama.httpx.get", return_value=mock_response):
        assert p.ping() is True


def test_ollama_ping_failure():
    p = OllamaProvider(model="llama3")

    with patch(
        "milco.llm.ollama.httpx.get", side_effect=Exception("connection refused")
    ):
        assert p.ping() is False
