#!/usr/bin/env python3
"""Ask the bullpen and block until the reply — the rich-agent "visit, ask, leave".
  room-ask [--from NICK] [--timeout N] @worker <question...>
Posts an `ask` addressed to @worker, waits for the `reply` that answers it, prints
the reply body. Exit 0 on reply, 1 on timeout/error. The wait is client-side (this
process), so it never blocks the lmcp server.
"""
import sys, json, subprocess, time, os, socket

# R4: bullpen.lua weist einen Post eines PRIVILEGIERTEN Nicks (markus, noether,
# foreman, ...) ohne dieses Secret mit "unauthorized" zurueck. Fuer einen nicht
# privilegierten Nick ignoriert das Gatter den Wert - mitschicken ist also immer
# richtig und nie schaedlich. Zwei Pfade, wie in bullpen_worker.py: der /etc-Pfad
# gehoert root (die Daemons laufen so), der Nutzerpfad ist fuer CLI-Aufrufer wie
# diesen hier gedacht.
def _post_secret():
    for p in ("/etc/bullpen/post-secret",
              os.path.expanduser("~/.config/bullpen/post-secret")):
        try:
            s = open(p).read().strip()
            if s:
                return s
        except OSError:
            pass
    return ""

POST_SECRET = _post_secret()

def lmcp(tool, **kw):
    return subprocess.run(["lmcp-tool", tool] + [f"{k}={v}" for k, v in kw.items()],
                          capture_output=True, text=True)

def main():
    args = sys.argv[1:]
    frm = os.environ.get("ROOM_NICK") or socket.gethostname().split(".")[0]
    # 90 statt 60: der Poll-Takt der Worker liegt seit 2026-08-03 bei 10 s
    # (0,1 Hz), ein gemessener Rundlauf mit @dispatcher dauerte 54 s.
    timeout = int(os.environ.get("ROOM_ASK_TIMEOUT", "90"))
    pos = []
    i = 0
    while i < len(args):
        if args[i] == "--from" and i + 1 < len(args): frm = args[i + 1]; i += 2
        elif args[i] == "--timeout" and i + 1 < len(args): timeout = int(args[i + 1]); i += 2
        else: pos.append(args[i]); i += 1
    if len(pos) < 2:
        print("usage: room-ask [--from NICK] [--timeout N] @worker <question>", file=sys.stderr)
        sys.exit(2)
    to = pos[0] if pos[0].startswith("@") else "@" + pos[0]
    body = " ".join(pos[1:])

    kw = {"from": frm, "to": to, "type": "ask", "body": body}
    if POST_SECRET:
        kw["secret"] = POST_SECRET
    r = lmcp("room_say", **kw)
    try:
        ask_id = json.loads(r.stdout.strip())["id"]
    except Exception:
        hinweis = ""
        if "unauthorized" in (r.stdout or "") and not POST_SECRET:
            hinweis = (f"\n  '{frm}' ist ein privilegierter Nick und braucht das Post-Secret."
                       "\n  Weder /etc/bullpen/post-secret noch ~/.config/bullpen/post-secret"
                       " war lesbar.")
        print(f"room-ask: post failed: {r.stdout}{r.stderr}{hinweis}", file=sys.stderr); sys.exit(1)

    deadline = time.time() + timeout
    while time.time() < deadline:
        for line in lmcp("room_read", since=ask_id).stdout.splitlines():
            line = line.strip()
            if not line: continue
            try: m = json.loads(line)
            except Exception: continue
            if m.get("type") == "reply" and m.get("in_reply_to") == ask_id:
                print(m.get("body", "")); sys.exit(0)
        time.sleep(1.5)
    print(f"room-ask: no reply from {to} within {timeout}s", file=sys.stderr); sys.exit(1)

if __name__ == "__main__":
    main()
