import asyncio
import websockets
import argparse
import time

async def receive_messages(stream_id):
    uri = f"ws://192.168.0.209:9999/ws/live/barrage/{stream_id}?access_token=59c74e75-32d5-4d15-ab99-fde861004502&TENANT-ID=1"
    
    while True:
        try:
            print(f"Connecting to {uri}...")
            async with websockets.connect(uri) as websocket:
                print(f"Listening on stream: {stream_id}")
                while True:
                    try:
                        message = await websocket.recv()
                        print(f"Received: {message}")
                    except websockets.exceptions.ConnectionClosed:
                        print("Connection closed")
                        break
        except Exception as e:
            print(f"Connection error: {e}")
        
        print("Reconnecting in 3 seconds...")
        await asyncio.sleep(3)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='WebSocket Receiver Client')
    parser.add_argument('stream_id', type=str, nargs='?', default=str(int(time.time())),
                        help='Stream ID (timestamp) to connect to. Should match the sender.')
    
    args = parser.parse_args()
    
    if args.stream_id is None:
        print("Warning: No stream_id provided. Using current timestamp, which might not match sender.")
        
    try:
        asyncio.run(receive_messages(123456))
    except KeyboardInterrupt:
        print("\nStopped by user")
