"""Tests for OpenAI-compatible provider (unit tests with mocked HTTP)."""

from unittest.mock import patch, MagicMock
from milco.llm.openai import OpenAIProvider


def test_openai_name():
    p = OpenAIProvider(model="gpt-4o", api_key="sk-test")
    assert p.name == "openai"


def test_openai_default_base_url():
    p = OpenAIProvider(model="gpt-4o", api_key="sk-test")
    assert p.base_url == "https://api.openai.com/v1"


def test_openai_custom_base_url():
    p = OpenAIProvider(
        model="local-model", api_key="none", base_url="http://localhost:1234/v1"
    )
    assert p.base_url == "http://localhost:1234/v1"


def test_openai_complete_calls_chat_api():
    p = OpenAIProvider(model="gpt-4o", api_key="sk-test")
    mock_response = MagicMock()
    mock_response.status_code = 200
    mock_response.json.return_value = {
        "choices": [{"message": {"content": "Hello back!"}}]
    }
    mock_response.raise_for_status = MagicMock()

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

    assert result == "Hello back!"
    call_kwargs = mock_post.call_args
    body = call_kwargs.kwargs.get("json") or call_kwargs[1].get("json")
    assert body["model"] == "gpt-4o"
    assert body["messages"][-1]["content"] == "Hello"


def test_openai_complete_with_system_prompt():
    p = OpenAIProvider(model="gpt-4o", api_key="sk-test")
    mock_response = MagicMock()
    mock_response.status_code = 200
    mock_response.json.return_value = {"choices": [{"message": {"content": "Sure!"}}]}
    mock_response.raise_for_status = MagicMock()

    with patch("milco.llm.openai.httpx.post", return_value=mock_response) as mock_post:
        p.complete("Do it", system="Be helpful")

    call_kwargs = mock_post.call_args
    body = call_kwargs.kwargs.get("json") or call_kwargs[1].get("json")
    messages = body["messages"]
    assert messages[0]["role"] == "system"
    assert messages[0]["content"] == "Be helpful"
    assert messages[1]["role"] == "user"


def test_openai_ping_success():
    p = OpenAIProvider(model="gpt-4o", api_key="sk-test")
    mock_response = MagicMock()
    mock_response.status_code = 200

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


def test_openai_ping_failure():
    p = OpenAIProvider(model="gpt-4o", api_key="sk-test")

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