#!/usr/bin/env python3
import asyncio, aiohttp, json, sys, time

async def poll():
    print(f"Poller started at {time.strftime('%H:%M:%S')}. Send a WhatsApp message...", flush=True)
    msgs_seen = 0
    for i in range(120):
        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] GOT {n} message(s)!', flush=True)
                            print(json.dumps(msgs[:3], indent=2), flush=True)
                            sys.exit(0)
                        elif i % 15 == 0:
                            print(f'[{i}s] queue empty', flush=True)
        except Exception as e:
            print(f'Error at t={i}s: {e}', flush=True)
        await asyncio.sleep(1)
    print('No messages in 120s', flush=True)

asyncio.run(poll())