#!/usr/bin/env python3
"""
Test script to verify the execution tracking system is working correctly.
This script tests the API endpoints and database operations.
"""

import requests
import json
import time
from datetime import datetime

# Configuration
BASE_URL = "http://localhost:5008"
API_BASE = f"{BASE_URL}/api"

def test_execution_tracking():
    """Test the execution tracking system"""
    print("🧪 Testing Execution Tracking System")
    print("=" * 50)
    
    # Test 1: Start execution
    print("\n1. Testing execution start...")
    start_data = {
        "testCaseId": "TC_FUNC_01_Test_Login",
        "userId": "test_user_123",
        "sessionId": "test_session_456"
    }
    
    try:
        response = requests.post(f"{API_BASE}/execution/start", json=start_data)
        if response.status_code == 200:
            data = response.json()
            if data.get('success'):
                execution_id = data.get('executionId')
                print(f"✅ Execution started successfully: {execution_id}")
            else:
                print(f"❌ Failed to start execution: {data.get('error')}")
                return False
        else:
            print(f"❌ HTTP Error: {response.status_code}")
            return False
    except Exception as e:
        print(f"❌ Exception: {e}")
        return False
    
    # Test 2: Update execution with results
    print("\n2. Testing execution update...")
    update_data = {
        "status": "passed",
        "summary": {
            "total": 1,
            "passed": 1,
            "failed": 0,
            "duration": 1500
        },
        "logs": [
            "Test Output:",
            "✅ Login test passed successfully",
            "Duration: 1500ms"
        ],
        "testCaseId": "TC_FUNC_01_Test_Login"
    }
    
    try:
        response = requests.post(f"{API_BASE}/execution/update/{execution_id}", json=update_data)
        if response.status_code == 200:
            data = response.json()
            if data.get('success'):
                print("✅ Execution updated successfully")
            else:
                print(f"❌ Failed to update execution: {data.get('error')}")
                return False
        else:
            print(f"❌ HTTP Error: {response.status_code}")
            return False
    except Exception as e:
        print(f"❌ Exception: {e}")
        return False
    
    # Test 3: Get execution by ID
    print("\n3. Testing get execution by ID...")
    try:
        response = requests.get(f"{API_BASE}/execution/{execution_id}")
        if response.status_code == 200:
            data = response.json()
            if data.get('success'):
                execution = data.get('execution')
                print(f"✅ Retrieved execution: {execution.get('status')} - {execution.get('testCaseId')}")
            else:
                print(f"❌ Failed to retrieve execution: {data.get('error')}")
                return False
        else:
            print(f"❌ HTTP Error: {response.status_code}")
            return False
    except Exception as e:
        print(f"❌ Exception: {e}")
        return False
    
    # Test 4: Get execution history
    print("\n4. Testing execution history...")
    try:
        response = requests.get(f"{API_BASE}/execution/history")
        if response.status_code == 200:
            data = response.json()
            if data.get('success'):
                executions = data.get('executions', [])
                print(f"✅ Retrieved {len(executions)} executions from history")
            else:
                print(f"❌ Failed to retrieve execution history: {data.get('error')}")
                return False
        else:
            print(f"❌ HTTP Error: {response.status_code}")
            return False
    except Exception as e:
        print(f"❌ Exception: {e}")
        return False
    
    # Test 5: Get execution stats
    print("\n5. Testing execution stats...")
    try:
        response = requests.get(f"{API_BASE}/execution/stats")
        if response.status_code == 200:
            data = response.json()
            if data.get('success'):
                stats = data.get('stats', {})
                print(f"✅ Retrieved stats: {stats.get('total')} total, {stats.get('success_rate')}% success rate")
            else:
                print(f"❌ Failed to retrieve execution stats: {data.get('error')}")
                return False
        else:
            print(f"❌ HTTP Error: {response.status_code}")
            return False
    except Exception as e:
        print(f"❌ Exception: {e}")
        return False
    
    print("\n🎉 All tests passed! Execution tracking system is working correctly.")
    return True

def test_website_pages():
    """Test that the website pages are accessible"""
    print("\n🌐 Testing Website Pages")
    print("=" * 30)
    
    pages = [
        "/execution-history",
        "/execution-report"
    ]
    
    for page in pages:
        try:
            response = requests.get(f"{BASE_URL}{page}")
            if response.status_code == 200:
                print(f"✅ {page} - Accessible")
            else:
                print(f"❌ {page} - HTTP {response.status_code}")
        except Exception as e:
            print(f"❌ {page} - Exception: {e}")

if __name__ == "__main__":
    print("🚀 AI Test Framework - Execution Tracking Test")
    print("=" * 60)
    
    # Test API endpoints
    success = test_execution_tracking()
    
    # Test website pages
    test_website_pages()
    
    if success:
        print("\n✅ All tests completed successfully!")
        print("\n📋 Next Steps:")
        print("1. Start the Flask server: python app.py")
        print("2. Start the desktop app: npm start (in desktop-app directory)")
        print("3. Visit http://localhost:5008/execution-history to see the execution history")
        print("4. Visit http://localhost:5008/execution-report to see the execution report")
        print("5. Run tests in the desktop app to see the new summary popup")
    else:
        print("\n❌ Some tests failed. Please check the server is running and try again.")
