# tests/test_main.py

from fastapi.testclient import TestClient
from unittest.mock import patch, MagicMock
from app.main import app
from app.llm_providers import get_llm_provider
# Create a TestClient instance based on our FastAPI app
client = TestClient(app)

def test_read_root():
    """Test the root endpoint to ensure it's running."""
    response = client.get("/")
    assert response.status_code == 200
    assert response.json() == {"status": "AI Model Hub is running!"}

@patch('app.main.client.chat.completions.create')
def test_chat_handler_success(mock_create):
    """Test the /chat endpoint with a successful, mocked API call."""
    # Configure the mock to return a predictable response
    mock_response = MagicMock()
    mock_response.choices = [MagicMock()]
    mock_response.choices[0].message = MagicMock()
    mock_response.choices[0].message.content = "This is a mock response from DeepSeek."
    mock_create.return_value = mock_response

    # Make the request to our app
    response = client.post("/chat", json={"prompt": "Hello there"})

    # Assert our app behaved as expected
    assert response.status_code == 200
    assert response.json() == {"response": "This is a mock response from DeepSeek."}
    # Verify that the mocked function was called
    mock_create.assert_called_once()

@patch('app.main.client.chat.completions.create')
def test_chat_handler_api_failure(mock_create):
    """Test the /chat endpoint when the external API fails."""
    # Configure the mock to raise an exception
    mock_create.side_effect = Exception("API connection error")

    # Make the request to our app
    response = client.post("/chat", json={"prompt": "This request will fail"})

    # Assert our app handles the error gracefully
    assert response.status_code == 500
    assert response.json() == {"detail": "Failed to get response from the model."}