"""
Simple test script for the Educational Content Evaluator API.

Usage:
    python -m src.api.test_api

This script tests the API endpoints locally without making actual LLM calls.
"""

import sys

from fastapi.testclient import TestClient

from .main import app

# Create test client
client = TestClient(app)


def test_health():
    """Test health check endpoint."""
    print("Testing /health endpoint...")
    response = client.get("/health")
    assert response.status_code == 200
    data = response.json()
    assert data["status"] == "healthy"
    assert "version" in data
    print(f"✓ Health check passed: {data}")


def test_curriculums():
    """Test curriculum listing endpoint."""
    print("\nTesting /curriculums endpoint...")
    response = client.get("/curriculums")
    assert response.status_code == 200
    data = response.json()
    assert "curriculums" in data
    assert "common_core" in data["curriculums"]
    print(f"✓ Curriculums endpoint passed: {data}")


def test_root():
    """Test root endpoint."""
    print("\nTesting / endpoint...")
    response = client.get("/")
    assert response.status_code == 200
    data = response.json()
    assert "service" in data
    assert "endpoints" in data
    print(f"✓ Root endpoint passed: {data['service']}")


def test_evaluate_validation():
    """Test evaluation endpoint input validation."""
    print("\nTesting /evaluate endpoint validation...")
    
    # Test missing content
    response = client.post("/evaluate", json={})
    assert response.status_code == 422  # Validation error
    print("✓ Validation: Missing content rejected")
    
    # Test empty content
    response = client.post("/evaluate", json={"content": ""})
    assert response.status_code == 422  # Validation error
    print("✓ Validation: Empty content rejected")
    
    # Test invalid curriculum
    response = client.post("/evaluate", json={
        "content": "Test content",
        "curriculum": "invalid_curriculum"
    })
    assert response.status_code == 400  # Bad request
    print("✓ Validation: Invalid curriculum rejected")


def test_evaluate_endpoint():
    """Test evaluation endpoint with valid input."""
    print("\nTesting /evaluate endpoint with valid input...")
    print("⚠️  This will make actual LLM API calls and may take time...")
    
    response = client.post("/evaluate", json={
        "content": "What is 2 + 2?",
        "curriculum": "common_core"
    })
    
    if response.status_code == 503:
        print("⚠️  Service unavailable (likely missing API keys)")
        print("   Set OPENAI_API_KEY and ANTHROPIC_API_KEY in .env file")
        return
    
    assert response.status_code == 200
    data = response.json()
    
    # Verify response structure
    assert "content_type" in data
    assert "overall" in data
    assert "factual_accuracy" in data
    assert "educational_accuracy" in data
    
    # Verify metric structure
    assert "score" in data["overall"]
    assert "reasoning" in data["overall"]
    
    print("✓ Evaluation successful:")
    print(f"  Content type: {data['content_type']}")
    print(f"  Overall score: {data['overall']['score']:.2f}")
    print(f"  Factual accuracy: {data['factual_accuracy']['score']:.2f}")


def main():
    """Run all tests."""
    print("=" * 70)
    print("Educational Content Evaluator API - Test Suite")
    print("=" * 70)
    
    try:
        # Basic endpoint tests (no LLM calls)
        test_health()
        test_curriculums()
        test_root()
        test_evaluate_validation()
        
        # Full evaluation test (requires API keys)
        test_evaluate_endpoint()
        
        print("\n" + "=" * 70)
        print("✓ All tests passed!")
        print("=" * 70)
        return 0
        
    except AssertionError as e:
        print(f"\n✗ Test failed: {e}")
        return 1
    except Exception as e:
        print(f"\n✗ Unexpected error: {e}")
        import traceback
        traceback.print_exc()
        return 1


if __name__ == "__main__":
    sys.exit(main())

