import asyncio
import os
import websockets
import json
import uuid

# Config: map to your domain/host via env (e.g. WEBSOCKET_HOST=10.0.0.109 for this server)
WEBSOCKET_HOST = os.getenv("WEBSOCKET_HOST", "10.0.0.109")
WEBSOCKET_PORT = int(os.getenv("WEBSOCKET_PORT", "7845"))
WEBSOCKET_PATH = os.getenv("WEBSOCKET_PATH", "voicebot_session_2002")

async def handle_client(websocket):
    """Handle incoming WebSocket connections and send unique ID"""
    try:
        # Generate a unique ID for this connection
        unique_id = str(uuid.uuid4())
        
        # Create response data
        response_data = {
            "unique_id": unique_id,
            "message": "Connection established successfully",
            "timestamp": str(asyncio.get_event_loop().time())
        }
        
        # Send the unique ID to the client
        await websocket.send(json.dumps(response_data))
        print(f"Sent unique ID: {unique_id} to client")
        
        # Keep connection alive and listen for any messages from client
        async for message in websocket:
            print(f"Received from client: {message}")
            # Echo back the message with the unique ID
            echo_response = {
                "unique_id": unique_id,
                "echo": message,
                "timestamp": str(asyncio.get_event_loop().time())
            }
            await websocket.send(json.dumps(echo_response))
            
    except websockets.exceptions.ConnectionClosed:
        print("Client disconnected")
    except Exception as e:
        print(f"Error handling client: {e}")

async def main():
    """Start the WebSocket server"""
    ws_url = f"ws://{WEBSOCKET_HOST}:{WEBSOCKET_PORT}/ws/{WEBSOCKET_PATH}"
    print(f"Starting WebSocket server on {ws_url}")
    print("Connect to this URL to get a unique ID")
    
    # Start the WebSocket server
    async with websockets.serve(handle_client, WEBSOCKET_HOST, WEBSOCKET_PORT):
        print("WebSocket server is running...")
        print(f"Available at: {ws_url}")
        print("Press Ctrl+C to stop the server")
        await asyncio.Future()  # Run forever

if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("\nServer stopped by user")
