#!/usr/bin/env python3
"""
Simple test for voice protocol without numpy dependency.
"""

import time
import sys
from protocol import IcingProtocol

# ANSI colors
RED = "\033[91m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
BLUE = "\033[94m"
RESET = "\033[0m"


def test_voice_protocol():
    """Test voice protocol with two peers."""
    print(f"\n{BLUE}=== Simple Voice Protocol Test ==={RESET}")
    print("Testing voice call setup and messaging.\n")
    
    # Create two protocol instances
    alice = IcingProtocol()
    bob = IcingProtocol()
    
    print(f"Alice listening on port: {alice.local_port}")
    print(f"Bob listening on port: {bob.local_port}")
    
    # Configure auto mode for easier testing
    alice.configure_auto_mode(
        active_mode=True,
        ping_auto_initiate=True,
        preferred_cipher=1,  # ChaCha20
    )
    
    bob.configure_auto_mode(
        ping_response_accept=True,
    )
    
    # Start auto mode
    alice.start_auto_mode()
    bob.start_auto_mode()
    
    # Exchange identity keys
    print(f"\n{YELLOW}1. Setting up secure channel...{RESET}")
    alice.set_peer_identity(bob.identity_pubkey.hex())
    bob.set_peer_identity(alice.identity_pubkey.hex())
    
    # Wait for servers to start
    time.sleep(0.5)
    
    # Establish connection - auto mode will handle the protocol
    alice.connect_to_peer(bob.local_port)
    
    # Wait for key exchange to complete
    print(f"\n{YELLOW}2. Waiting for automatic key exchange...{RESET}")
    max_wait = 10
    for i in range(max_wait):
        time.sleep(1)
        if alice.state.get("key_exchange_complete") and bob.state.get("key_exchange_complete"):
            print(f"{GREEN}   Key exchange completed!{RESET}")
            break
        print(f"   Waiting... {i+1}/{max_wait}")
    else:
        print(f"{RED}   Key exchange failed to complete{RESET}")
        alice.stop()
        bob.stop()
        return
    
    # Test voice call
    print(f"\n{YELLOW}3. Testing voice call setup...{RESET}")
    
    # Alice initiates voice call
    success = alice.start_voice_call(codec_mode=5, fec_type=0)
    if success:
        print(f"{GREEN}   Alice initiated voice call{RESET}")
    else:
        print(f"{RED}   Failed to initiate voice call{RESET}")
        alice.stop()
        bob.stop()
        return
    
    # Wait for Bob to receive and auto-accept
    time.sleep(1)
    
    # Check voice status
    print(f"\n{YELLOW}4. Voice call status:{RESET}")
    print(f"   Alice voice active: {alice.voice_session_active}")
    print(f"   Bob voice active: {bob.voice_session_active}")
    
    if alice.voice_session_active and bob.voice_session_active:
        print(f"{GREEN}   Voice call established successfully!{RESET}")
        print(f"   Session ID: {alice.voice_session_id:016x}")
        
        # Test sending encrypted messages during voice call
        print(f"\n{YELLOW}5. Testing encrypted messaging during voice call...{RESET}")
        alice.send_encrypted_message("Voice call test message from Alice")
        time.sleep(0.5)
        
        # Bob decrypts
        for i, msg in enumerate(bob.inbound_messages):
            if msg["type"] == "ENCRYPTED_MESSAGE":
                plaintext = bob.decrypt_received_message(i)
                if plaintext:
                    print(f"   Bob received: {plaintext}")
        
        # End voice call
        print(f"\n{YELLOW}6. Ending voice call...{RESET}")
        alice.end_voice_call()
        time.sleep(0.5)
        
        print(f"   Voice call ended")
    else:
        print(f"{RED}   Voice call failed to establish{RESET}")
    
    # Show final states
    print(f"\n{YELLOW}7. Final states:{RESET}")
    print("\nAlice state:")
    alice.show_state()
    print("\nBob state:")
    bob.show_state()
    
    # Cleanup
    alice.stop()
    bob.stop()
    
    print(f"\n{GREEN}Test completed!{RESET}")


if __name__ == "__main__":
    try:
        test_voice_protocol()
    except KeyboardInterrupt:
        print(f"\n{YELLOW}Test interrupted.{RESET}")
    except Exception as e:
        print(f"\n{RED}ERROR: {e}{RESET}")
        import traceback
        traceback.print_exc()