"""
Test script for the data service
"""
import asyncio
import aiohttp
import json
from datetime import datetime


async def test_data_service():
    """Test the data service endpoints"""
    base_url = "http://localhost:8003"
    
    async with aiohttp.ClientSession() as session:
        print("Testing Data Service...")
        
        # Test health endpoint
        print("\n1. Testing health endpoint...")
        try:
            async with session.get(f"{base_url}/health") as response:
                if response.status == 200:
                    data = await response.json()
                    print(f"✅ Health check passed: {data}")
                else:
                    print(f"❌ Health check failed: {response.status}")
        except Exception as e:
            print(f"❌ Health check error: {e}")
        
        # Test root endpoint
        print("\n2. Testing root endpoint...")
        try:
            async with session.get(f"{base_url}/") as response:
                if response.status == 200:
                    data = await response.json()
                    print(f"✅ Root endpoint passed: {data}")
                else:
                    print(f"❌ Root endpoint failed: {response.status}")
        except Exception as e:
            print(f"❌ Root endpoint error: {e}")
        
        # Test search engines
        print("\n3. Testing search engines...")
        try:
            test_query = "artificial intelligence"
            async with session.get(f"{base_url}/api/v1/scraper/test-search?query={test_query}&engine=google") as response:
                if response.status == 200:
                    data = await response.json()
                    print(f"✅ Google search test passed: Found {data.get('results_count', 0)} results")
                else:
                    print(f"❌ Google search test failed: {response.status}")
                    error_data = await response.text()
                    print(f"Error: {error_data}")
        except Exception as e:
            print(f"❌ Google search test error: {e}")
        
        # Test starting a search job
        print("\n4. Testing search job creation...")
        try:
            search_request = {
                "query": "machine learning",
                "search_engines": ["google"],
                "max_results": 5,
                "created_by": "test_user"
            }
            
            async with session.post(
                f"{base_url}/api/v1/scraper/search",
                json=search_request
            ) as response:
                if response.status == 200:
                    data = await response.json()
                    job_id = data.get('job_id')
                    print(f"✅ Search job created: {job_id}")
                    
                    # Wait a bit and check job status
                    await asyncio.sleep(2)
                    
                    async with session.get(f"{base_url}/api/v1/scraper/jobs/{job_id}/status") as status_response:
                        if status_response.status == 200:
                            status_data = await status_response.json()
                            print(f"✅ Job status: {status_data.get('status')}")
                        else:
                            print(f"❌ Job status check failed: {status_response.status}")
                else:
                    print(f"❌ Search job creation failed: {response.status}")
                    error_data = await response.text()
                    print(f"Error: {error_data}")
        except Exception as e:
            print(f"❌ Search job creation error: {e}")
        
        # Test articles endpoint
        print("\n5. Testing articles endpoint...")
        try:
            async with session.get(f"{base_url}/api/v1/articles/?page=1&page_size=5") as response:
                if response.status == 200:
                    data = await response.json()
                    print(f"✅ Articles endpoint passed: Found {data.get('total_count', 0)} articles")
                else:
                    print(f"❌ Articles endpoint failed: {response.status}")
        except Exception as e:
            print(f"❌ Articles endpoint error: {e}")
        
        # Test scraper stats
        print("\n6. Testing scraper stats...")
        try:
            async with session.get(f"{base_url}/api/v1/scraper/stats") as response:
                if response.status == 200:
                    data = await response.json()
                    print(f"✅ Scraper stats passed: {data.get('total_jobs', 0)} total jobs")
                else:
                    print(f"❌ Scraper stats failed: {response.status}")
        except Exception as e:
            print(f"❌ Scraper stats error: {e}")
        
        # Test article stats
        print("\n7. Testing article stats...")
        try:
            async with session.get(f"{base_url}/api/v1/articles/stats/overview") as response:
                if response.status == 200:
                    data = await response.json()
                    print(f"✅ Article stats passed: {data.get('total_articles', 0)} total articles")
                else:
                    print(f"❌ Article stats failed: {response.status}")
        except Exception as e:
            print(f"❌ Article stats error: {e}")
        
        print("\n🎉 Data service testing completed!")


if __name__ == "__main__":
    print("Data Service Test Suite")
    print("=" * 50)
    print("Make sure the data service is running on http://localhost:8003")
    print("You can start it with: uvicorn main:app --host 0.0.0.0 --port 8003 --reload")
    print("=" * 50)
    
    asyncio.run(test_data_service())