#!/usr/bin/env python3
"""
Simple WebSocket test for hwGpt basic connectivity.
This tests the simple WebSocket endpoint without complex logic.
"""

import asyncio
import websockets
import json
import logging

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


async def test_simple_websocket():
    """Test the simple WebSocket endpoint."""
    uri = "ws://localhost:8000/hw_gpt/simple-test/1/35"
    
    try:
        logger.info(f"Connecting to: {uri}")
        
        async with websockets.connect(uri) as websocket:
            logger.info("✅ WebSocket connected successfully!")
            
            # Wait for connection message
            try:
                response = await asyncio.wait_for(websocket.recv(), timeout=5.0)
                data = json.loads(response)
                logger.info(f"📥 Received: {data}")
                
                if data.get("type") == "connection_established":
                    logger.info("✅ Connection established message received!")
                else:
                    logger.warning(f"Unexpected message type: {data.get('type')}")
                    
            except asyncio.TimeoutError:
                logger.warning("⏰ No response received within 5 seconds")
                return
            
            # Test sending a simple message
            test_message = {
                "type": "chat",
                "message": "Hello! This is a test message."
            }
            
            logger.info(f"📤 Sending test message: {test_message}")
            await websocket.send(json.dumps(test_message))
            
            # Wait for echo response
            try:
                response = await asyncio.wait_for(websocket.recv(), timeout=5.0)
                data = json.loads(response)
                logger.info(f"📥 Received echo: {data}")
                
                if data.get("type") == "echo":
                    logger.info("✅ Echo response received successfully!")
                else:
                    logger.warning(f"Unexpected response type: {data.get('type')}")
                
            except asyncio.TimeoutError:
                logger.warning("⏰ No echo response received within 5 seconds")
            
            logger.info("✅ Simple WebSocket test completed successfully!")
            
    except Exception as e:
        logger.error(f"❌ Simple WebSocket test failed: {str(e)}")
        import traceback
        traceback.print_exc()


if __name__ == "__main__":
    print("🚀 Simple WebSocket Test for hwGpt")
    print("=" * 50)
    print("Make sure your FastAPI server is running on localhost:8000")
    print("This tests the basic WebSocket connectivity")
    print()
    
    # Test simple connection
    print("1️⃣ Testing simple WebSocket connection...")
    asyncio.run(test_simple_websocket())
    
    print("\n�� Test completed!")
