#!/usr/bin/env python3
"""
Improved debug script to test keyboard controls and private chat functionality.
"""

import time
import requests
from src.facades.game_facade import GameFacade
from src.services.chat_service import ChatService
from src.core.game_engine import get_game_engine

def test_keyboard_backend():
    """Test keyboard controls backend functionality."""
    print("๐ŸŽฎ Testing Keyboard Controls Backend")
    print("=" * 60)
    
    try:
        # Initialize game facade
        facade = GameFacade()
        
        # Create test player
        player_id = facade.join_game("KeyboardTester")
        print(f"โœ… Test player created: {player_id}")
        
        # Get initial player data
        try:
            player_stats = facade.get_player_stats(player_id)
            print(f"๐Ÿ“ Initial position: ({player_stats.get('x', '?')}, {player_stats.get('y', '?')})")
        except Exception as e:
            print(f"โš ๏ธ Could not get initial position: {e}")
        
        # Test all movement directions (what keyboard would trigger)
        movements = [
            ("up", "๐Ÿ”ผ", "W/โ†‘"),
            ("down", "๐Ÿ”ฝ", "S/โ†“"), 
            ("left", "โ—€๏ธ", "A/โ†"),
            ("right", "โ–ถ๏ธ", "D/โ†’")
        ]
        
        print("\n๐ŸŽฏ Testing movement commands (keyboard backend):")
        for direction, icon, keys in movements:
            try:
                print(f"   {icon} Testing {direction} movement (keys: {keys})...")
                success, new_position, events = facade.move_player(player_id, direction)
                
                if success:
                    print(f"      โœ… Success - New position: ({new_position.get('x', '?')}, {new_position.get('y', '?')})")
                    if events:
                        print(f"      ๐Ÿ“ Events: {', '.join(events)}")
                else:
                    print(f"      โŒ Failed - Movement blocked")
                    
                time.sleep(0.3)  # Small delay between movements
                
            except Exception as e:
                print(f"      โŒ Error: {str(e)}")
        
        # Test action command (spacebar equivalent)
        print(f"\nโšก Testing special action (spacebar)...")
        try:
            result = facade.handle_action(player_id)
            print(f"   โœ… Result: {result}")
        except Exception as e:
            print(f"   โŒ Error: {str(e)}")
        
        # Cleanup
        facade.leave_game(player_id)
        print(f"\n๐Ÿงน Cleanup: Player {player_id} removed")
        
        return True
        
    except Exception as e:
        print(f"โŒ Keyboard backend test failed: {str(e)}")
        return False

def test_private_chat_backend():
    """Test private chat backend functionality."""
    print("\n๐Ÿ’ฌ Testing Private Chat Backend")
    print("=" * 60)
    
    try:
        # Initialize services
        facade = GameFacade()
        engine = get_game_engine()
        world = engine.get_world()
        
        # Create test players
        player1_id = facade.join_game("ChatTester1")
        player2_id = facade.join_game("ChatTester2")
        print(f"โœ… Test players created: {player1_id}, {player2_id}")
        
        # Move players close to each other for proximity
        print("\n๐Ÿšถ Moving players close to each other...")
        facade.move_player(player1_id, "right")
        facade.move_player(player1_id, "right")
        facade.move_player(player2_id, "right")
        
        # Test proximity detection
        print(f"\n๐Ÿ‘ฅ Testing proximity detection...")
        try:
            proximity_data = facade.get_proximity_info(player1_id)
            nearby_entities = proximity_data.get("nearby_entities", [])
            print(f"   โœ… Found {len(nearby_entities)} nearby entities")
            for entity in nearby_entities:
                print(f"      - {entity.get('name', entity.get('id', 'Unknown'))}")
        except Exception as e:
            print(f"   โŒ Proximity error: {str(e)}")
          # Test private message sending
        print(f"\n๐Ÿ“ค Testing private message sending...")
        try:
            result = facade.send_private_message(
                player1_id,
                "ChatTester1", 
                player2_id,
                "Hello from private chat test!"
            )
            print(f"   {'โœ… Message sent successfully' if result else 'โŒ Message failed to send'}")
        except Exception as e:
            print(f"   โŒ Send error: {str(e)}")
        
        # Test message retrieval
        print(f"\n๐Ÿ“ฅ Testing private message retrieval...")
        try:
            messages = facade.get_private_messages(player1_id, player2_id)
            print(f"   โœ… Retrieved {len(messages)} private messages")
            for i, msg in enumerate(messages[-2:], 1):  # Show last 2 messages
                sender = msg.get('sender_id', 'Unknown')
                content = msg.get('message', 'No content')
                timestamp = msg.get('timestamp', 'No time')
                print(f"      {i}. [{timestamp}] {sender}: {content}")
        except Exception as e:
            print(f"   โŒ Retrieval error: {str(e)}")
        
        # Test public chat (for comparison)
        print(f"\n๐Ÿ“ข Testing public chat...")
        try:
            result = facade.send_chat_message(player1_id, "Hello public chat!")
            print(f"   {'โœ… Public message sent' if result else 'โŒ Public message failed'}")
            
            history = facade.get_chat_history(5)
            print(f"   โœ… Retrieved {len(history)} chat history entries")
        except Exception as e:
            print(f"   โŒ Public chat error: {str(e)}")
        
        # Cleanup
        facade.leave_game(player1_id)
        facade.leave_game(player2_id)
        print(f"\n๐Ÿงน Cleanup: Test players removed")
        
        return True
        
    except Exception as e:
        print(f"โŒ Private chat backend test failed: {str(e)}")
        return False

def test_frontend_integration():
    """Test frontend integration and JavaScript presence."""
    print("\n๐ŸŒ Testing Frontend Integration")
    print("=" * 60)
    
    try:
        # Test main application URL
        print("๐Ÿ“ก Testing main application...")
        response = requests.get("http://localhost:7865", timeout=10)
        print(f"   Status: {'โœ… Online' if response.status_code == 200 else 'โŒ Error'}")
        print(f"   Response time: {response.elapsed.total_seconds():.2f}s")
        print(f"   Content length: {len(response.content)} bytes")
        
        # Check for keyboard script presence
        print("\nโŒจ๏ธ Checking keyboard script integration...")
        content_lower = response.text.lower()
        
        checks = [
            ("gameKeyboard object", "gamekeyboard" in content_lower),
            ("WASD controls", "wasd" in content_lower),
            ("Arrow keys", "arrow" in content_lower),
            ("Key event handlers", "keydown" in content_lower or "keypress" in content_lower),
            ("Movement buttons", "move" in content_lower and "button" in content_lower),
        ]
        
        for check_name, check_result in checks:
            status = "โœ… Found" if check_result else "โŒ Missing"
            print(f"   {status}: {check_name}")
        
        # Check for private chat elements
        print("\n๐Ÿ’ฌ Checking private chat integration...")
        chat_checks = [
            ("Private chat UI", "private" in content_lower and "chat" in content_lower),
            ("Nearby entities", "nearby" in content_lower),
            ("Chat tabs", "tab" in content_lower),
            ("Message input", "message" in content_lower),
        ]
        
        for check_name, check_result in chat_checks:
            status = "โœ… Found" if check_result else "โŒ Missing"
            print(f"   {status}: {check_name}")
        
        # Check for enhanced features
        print("\n๐ŸŽจ Checking enhanced features...")
        enhanced_checks = [
            ("Player glow effect", "border" in content_lower and "yellow" in content_lower),
            ("Player names", "name" in content_lower and "level" in content_lower),
            ("Status line", "fantasy realm" in content_lower),
            ("Movement controls", "movement" in content_lower and "controls" in content_lower),
        ]
        
        for check_name, check_result in enhanced_checks:
            status = "โœ… Found" if check_result else "โŒ Missing"
            print(f"   {status}: {check_name}")
        
        return True
        
    except Exception as e:
        print(f"โŒ Frontend integration test failed: {str(e)}")
        return False

def main():
    """Run comprehensive debug tests with improved logging."""
    print("๐Ÿ” MMORPG Debug Test - Keyboard & Private Chat")
    print("=" * 70)
    print("Testing backend functionality and frontend integration...")
    
    # Run all tests
    keyboard_ok = test_keyboard_backend()
    chat_ok = test_private_chat_backend()
    frontend_ok = test_frontend_integration()
    
    # Summary
    print("\n" + "=" * 70)
    print("๐Ÿ“Š COMPREHENSIVE TEST SUMMARY")
    print("=" * 70)
    print(f"๐ŸŽฎ Keyboard Backend:    {'โœ… PASS' if keyboard_ok else 'โŒ FAIL'}")
    print(f"๐Ÿ’ฌ Private Chat Backend: {'โœ… PASS' if chat_ok else 'โŒ FAIL'}")
    print(f"๐ŸŒ Frontend Integration: {'โœ… PASS' if frontend_ok else 'โŒ FAIL'}")
    
    if all([keyboard_ok, chat_ok, frontend_ok]):
        print("\n๐ŸŽ‰ ALL TESTS PASSED!")
        print("\nโœจ Next steps for manual testing:")
        print("   1. Open http://localhost:7865 in your browser")
        print("   2. Join the game with a player name")
        print("   3. Test keyboard controls: WASD or Arrow keys")
        print("   4. Test spacebar for special actions")
        print("   5. Move near other players/NPCs for private chat")
        print("   6. Use the private chat interface")
    elif keyboard_ok and chat_ok:
        print("\nโš ๏ธ Backend working, but frontend integration issues detected.")
        print("\n๐Ÿ”ง Recommended fixes:")
        print("   - Check browser console for JavaScript errors")
        print("   - Verify keyboard script is properly loaded")
        print("   - Ensure buttons have correct IDs for script binding")
    else:
        print("\nโŒ Backend issues detected - need to fix core functionality first.")
    
    print("\n๐ŸŒ Application URL: http://localhost:7865")
    print("=" * 70)

if __name__ == "__main__":
    main()