#!/usr/bin/env python3
"""
Test script for different OCPP drivers
"""
import asyncio
import subprocess
import time
import sys
import os

def test_driver(driver_name, port):
    """Test a specific driver"""
    print(f"\n🧪 Testing {driver_name.upper()} driver on port {port}")
    print("=" * 50)
    
    # Set environment variables
    env = os.environ.copy()
    env.update({
        'BACKEND_URL': 'http://test.com',
        'DRIVER': driver_name,
        'UDP_PORT': str(port),
        'LOG_LEVEL': 'INFO'
    })
    
    # Start the client server
    try:
        process = subprocess.Popen(
            [sys.executable, '-m', 'client.server'],
            env=env,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            text=True
        )
        
        # Give server time to start
        time.sleep(2)
        
        # Send test messages
        test_messages = [
            '{"action": "Heartbeat"}',
            '{"action": "BootNotification", "payload": {"chargePointVendor": "TestVendor", "chargePointModel": "TestModel"}}',
            '{"action": "StatusNotification", "payload": {"connectorId": 1, "status": "Available", "errorCode": "NoError"}}'
        ]
        
        for i, message in enumerate(test_messages, 1):
            print(f"\n📤 Sending test message {i}: {message[:50]}...")
            subprocess.run(['nc', '-u', '127.0.0.1', str(port)], 
                         input=message, text=True, timeout=2)
            time.sleep(1)
        
        print(f"\n✅ {driver_name.upper()} driver test completed!")
        
    except Exception as e:
        print(f"❌ Error testing {driver_name} driver: {e}")
    finally:
        if process:
            process.terminate()
            process.wait()

def main():
    """Main test function"""
    print("🚀 Starting OCPP Driver Tests")
    print("This will test file, console, and null drivers")
    
    drivers_and_ports = [
        ('file', 9100),
        ('console', 9101), 
        ('null', 9102)
    ]
    
    for driver, port in drivers_and_ports:
        test_driver(driver, port)
        time.sleep(2)  # Wait between tests
    
    print("\n🎉 All driver tests completed!")
    print("\n📁 Check events.log for file driver output")

if __name__ == "__main__":
    main()
