#!/usr/bin/env python3
"""Simple auto test for the integrated UI - tests basic functionality"""

import sys
import time
import subprocess
from pathlib import Path

# Add parent directory to path
sys.path.insert(0, str(Path(__file__).parent))
sys.path.insert(0, str(Path(__file__).parent.parent))

from integrated_protocol import IntegratedDryBoxProtocol

def test_basic_connection():
    """Test basic protocol connection and key exchange"""
    print("="*50)
    print("Simple Auto Test")
    print("="*50)
    
    # Create two protocol instances
    print("\n1. Creating protocol instances...")
    phone1 = IntegratedDryBoxProtocol(mode="sender")
    phone2 = IntegratedDryBoxProtocol(mode="receiver")
    
    print(f"✓ Phone 1 (sender) created - Port: {phone1.protocol.local_port}")
    print(f"✓ Phone 2 (receiver) created - Port: {phone2.protocol.local_port}")
    
    # Exchange identities
    print("\n2. Exchanging identities...")
    phone1_id = phone1.get_identity_key()
    phone2_id = phone2.get_identity_key()
    
    print(f"✓ Phone 1 identity: {phone1_id[:32]}...")
    print(f"✓ Phone 2 identity: {phone2_id[:32]}...")
    
    # Connect to GSM simulator
    print("\n3. Connecting to GSM simulator...")
    
    # Check if GSM simulator is running by trying to connect
    import socket
    try:
        test_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        test_sock.settimeout(1)
        test_sock.connect(("localhost", 12345))
        test_sock.close()
        print("✓ GSM simulator is running")
    except:
        print("❌ GSM simulator not running. Start it with: python3 gsm_simulator.py")
        return False
    
    if not phone1.connect_gsm():
        print("❌ Phone 1 failed to connect to GSM")
        return False
    
    if not phone2.connect_gsm():
        print("❌ Phone 2 failed to connect to GSM")
        return False
        
    print("✓ Both phones connected to GSM simulator")
    
    # Setup protocol connections
    print("\n4. Setting up protocol connections...")
    phone1.setup_protocol_connection(
        peer_port=phone2.protocol.local_port,
        peer_identity=phone2_id
    )
    
    phone2.setup_protocol_connection(
        peer_port=phone1.protocol.local_port,
        peer_identity=phone1_id
    )
    
    time.sleep(1)  # Give connections time to establish
    print("✓ Protocol connections established")
    
    # Test ChaCha20 key exchange
    print("\n5. Testing ChaCha20-Poly1305 key exchange...")
    if phone1.initiate_key_exchange(cipher_type=1):
        print("✓ Key exchange successful")
        print(f"  Cipher: ChaCha20-Poly1305")
        print(f"  HKDF Key: {phone1.protocol.hkdf_key[:32]}...")
        
        # Send test message
        print("\n6. Testing encrypted message...")
        test_msg = "Hello from automated test!"
        phone1.send_encrypted_message(test_msg)
        time.sleep(1)
        print(f"✓ Sent encrypted message: {test_msg}")
        
        # Test voice if available
        if Path("input.wav").exists():
            print("\n7. Testing voice transmission...")
            phone1.send_voice()
            print("✓ Voice transmission initiated")
        else:
            print("\n7. Skipping voice test (input.wav not found)")
    else:
        print("❌ Key exchange failed")
        return False
    
    # Cleanup
    print("\n8. Cleaning up...")
    phone1.close()
    phone2.close()
    print("✓ Protocols closed")
    
    print("\n" + "="*50)
    print("✓ All tests passed!")
    print("="*50)
    return True

if __name__ == "__main__":
    if test_basic_connection():
        sys.exit(0)
    else:
        sys.exit(1)