#!/usr/bin/env python3
"""Watch bridge queue for incoming messages."""
import asyncio, aiohttp, json, sys, time

async def watch():
    print(f"Watching bridge queue from {time.strftime('%H:%M:%S')}. Send a WhatsApp message...", flush=True)
    for i in range(180):
        try:
            async with aiohttp.ClientSession() as s:
                async with s.get('http://127.0.0.1:3000/messages', timeout=aiohttp.ClientTimeout(total=5)) as resp:
                    if resp.status == 200:
                        msgs = await resp.json()
                        n = len(msgs)
                        if n > 0:
                            print(f'[{i}s] RECEIVED {n} message(s):', flush=True)
                            for m in msgs:
                                print(f'  From: {m.get("senderId")} | Body: {m.get("body", "")[:100]}', flush=True)
                            sys.exit(0)
        except Exception as e:
            print(f'[{i}s] error: {e}', flush=True)
        if i % 30 == 0:
            print(f'[{i}s] still watching...', flush=True)
        await asyncio.sleep(1)
    print('No messages in 180s', flush=True)

asyncio.run(watch())