"""
Monitor XMPP group messages from the HTTP bridge.
Prints new messages as they arrive. Press Ctrl+C to stop.
Usage: python watch_group.py [--from mohe]
"""
import sys, time, json, urllib.request

URL = "http://127.0.0.1:5802/messages"
SENDER = None

args = sys.argv[1:]
for i, a in enumerate(args):
    if a == "--from" and i + 1 < len(args):
        SENDER = args[i + 1]

last_ts = ""

while True:
    try:
        url = URL
        if SENDER:
            url += f"?from={SENDER}"
        resp = urllib.request.urlopen(url, timeout=5)
        data = json.loads(resp.read())
        msgs = data.get("messages", [])
        new_msgs = [m for m in msgs if m["ts"] > last_ts]
        for m in new_msgs:
            last_ts = m["ts"]
            sender_tag = f"[{m['from']}]"
            print(f"\n{sender_tag} {m['body']}")
            print("---")
        if new_msgs:
            print(f"\n({len(new_msgs)} new, waiting...)", flush=True)
    except Exception as e:
        print(f"(poll error: {e})", flush=True)
    time.sleep(3)
