#!/usr/bin/env python3
import requests
import time
import sys

def test_central_server():
    """Testa la connessione al central server"""
    try:
        print("🧪 Testing Central Server connection...")
        response = requests.get("http://localhost:5000/api/health", timeout=5)
        if response.status_code == 200:
            print("✅ Central Server is ONLINE")
            return True
        else:
            print(f"❌ Central Server responded with: {response.status_code}")
            return False
    except Exception as e:
        print(f"❌ Central Server is OFFLINE: {e}")
        return False

def test_registration():
    """Testa la registrazione di un coordinator fittizio"""
    try:
        print("🧪 Testing registration endpoint...")
        test_data = {
            'coordinator_id': 'test_coord_123',
            'host': 'localhost',
            'port': 8765,
            'current_workers': 1,
            'total_gpu_memory': 16304,
            'performance_score': 1.7
        }
        
        response = requests.post(
            "http://localhost:5000/api/register_coordinator",
            json=test_data,
            timeout=10
        )
        
        if response.status_code == 200:
            print("✅ Registration endpoint WORKING")
            return True
        else:
            print(f"❌ Registration failed: {response.status_code} - {response.text}")
            return False
    except Exception as e:
        print(f"❌ Registration test failed: {e}")
        return False

def check_current_status():
    """Controlla lo stato attuale del central server"""
    try:
        response = requests.get("http://localhost:5000/api/debug", timeout=5)
        data = response.json()
        
        print("\n📊 CURRENT CENTRAL SERVER STATUS:")
        print(f"   Coordinators: {data['total_coordinators']}")
        print(f"   Workers: {data['total_workers']}")
        print(f"   Memory: {data['total_memory']}MB")
        
        if data['total_coordinators'] > 0:
            print("   ✅ Coordinators are registered!")
        else:
            print("   ⚠️ No coordinators registered")
            
        return data
    except Exception as e:
        print(f"❌ Status check failed: {e}")
        return None

if __name__ == "__main__":
    print("🚀 STARTING INTEGRATION TEST")
    print("=" * 50)
    
    # Test 1: Central Server connectivity
    if not test_central_server():
        print("\n💡 SOLUTION: Start Central Server with:")
        print("   python central_server_debug.py")
        sys.exit(1)
    
    # Test 2: Registration endpoint
    if not test_registration():
        print("\n💡 SOLUTION: Check Central Server logs for errors")
        sys.exit(1)
    
    # Test 3: Current status
    status = check_current_status()
    
    print("\n" + "=" * 50)
    if status and status['total_coordinators'] > 0:
        print("🎉 ALL TESTS PASSED - System is WORKING!")
    else:
        print("🔧 NEXT STEPS:")
        print("   1. Ensure Central Server is running")
        print("   2. Check Coordinator logs for registration attempts")
        print("   3. Verify network connectivity between services")
        print("   4. Check firewall/port settings")