"""
Mohe reply watcher — polls HTTP bridge every 30s for new mohe messages.
Logs new replies to logs/mohe_inbox.log. Runs as persistent background process.

Start: python mohe_watcher.py
"""
import os, sys, time, json, urllib.request

PROJECT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
LOG = os.path.join(PROJECT, "logs", "mohe_inbox.log")
os.makedirs(os.path.dirname(LOG), exist_ok=True)

def log(msg: str):
    ts = time.strftime("%Y-%m-%d %H:%M:%S")
    with open(LOG, "a", encoding="utf-8") as f:
        f.write(f"{ts} {msg}\n")

last_ts = ""

log("mohe_watcher started")

while True:
    try:
        url = "http://127.0.0.1:5802/messages?from=mohe"
        resp = urllib.request.urlopen(url, timeout=5)
        data = json.loads(resp.read())
        msgs = data.get("messages", [])

        new = [m for m in msgs if m["ts"] > last_ts]
        if new:
            for m in new:
                log(f"[{m['ts']}] mohe: {m['body']}")
            last_ts = new[-1]["ts"]
        elif msgs and not last_ts:
            # First run — record last timestamp but don't replay old messages
            last_ts = msgs[-1]["ts"]
    except Exception as e:
        log(f"(poll error: {e})")

    time.sleep(30)
