# integration_tests/test_service.py

import requests
import os
from dotenv import load_dotenv

# --- Configuration ---
# The base URL for our running service.
# Note: We use http://ai-hub:8000 when running Docker-to-Docker,
# but http://127.0.0.1:8000 when running from the host machine.
# For simplicity, we will run this script from the host.
BASE_URL = "http://127.0.0.1:8000"

# Load the .env file to check if the API key is set
load_dotenv()
API_KEY = os.getenv("DEEPSEEK_API_KEY")

def test_root_endpoint():
    """Checks if the service is alive."""
    print("Testing root endpoint...")
    response = requests.get(f"{BASE_URL}/")
    
    assert response.status_code == 200
    assert response.json()["status"] == "AI Model Hub is running!"
    print("Root endpoint test: PASSED")

def test_chat_endpoint():
    """
    Sends a real prompt to the /chat endpoint and verifies a valid response.
    This will make a REAL API call to DeepSeek and requires a valid key.
    """
    print("\nTesting /chat endpoint...")
    if not API_KEY or "YOUR_API_KEY" in API_KEY:
        print("SKIPPING test: DEEPSEEK_API_KEY not set in .env file.")
        return

    json_payload = {"prompt": "Explain what an integration test is in one sentence."}
    
    try:
        response = requests.post(f"{BASE_URL}/chat", json=json_payload, timeout=30)
        
        # Check for successful HTTP status
        assert response.status_code == 200
        
        # Check the response body
        data = response.json()
        assert "response" in data
        assert isinstance(data["response"], str)
        assert len(data["response"]) > 0
        
        print(f"Received response: '{data['response']}'")
        print("/chat endpoint test: PASSED")

    except requests.exceptions.RequestException as e:
        print(f"/chat endpoint test: FAILED - {e}")
        assert False, f"Request failed: {e}"

if __name__ == "__main__":
    print("--- Running Integration Tests ---")
    test_root_endpoint()
    test_chat_endpoint()
    print("\n--- All tests completed ---")