#!/usr/bin/env python3
"""room-post — put a long body into the room from a FILE.

`lmcp-tool` takes the body as a command-line argument. For a contract text of
seventy lines that is the wrong channel: quotes, dollar signs and newlines would
have to survive two shells and a container. So it is read here and sent as JSON —
the text never touches a command line, and neither does the secret.

    room-post <from> <to> <file> [<secret-file>] [--type ask] [--in-reply-to N]

`--type` was missing until 2026-08-09, so this could only ever post `chat`. A
waking `ask` had to go through lmcp-tool instead, which put the body back on a
command line — exactly what this program exists to avoid. `--in-reply-to` for the
same reason: a long answer could not be bound to its question.
"""
import argparse
import json
import os
import sys
import urllib.request


def main():
    ap = argparse.ArgumentParser(add_help=False)
    ap.add_argument("von")
    ap.add_argument("an")
    ap.add_argument("datei")
    ap.add_argument("geheimnis", nargs="?")
    ap.add_argument("--type", dest="typ", default=None,
                    help="chat (default), ask to wake a worker, system, reply")
    ap.add_argument("--in-reply-to", dest="in_reply_to", type=int, default=None)
    ap.add_argument("-h", "--help", action="help")
    a = ap.parse_args()

    args = {"from": a.von, "to": a.an, "body": open(a.datei, encoding="utf-8").read()}
    if a.typ:
        args["type"] = a.typ
    if a.in_reply_to is not None:
        args["in_reply_to"] = a.in_reply_to
    # Privileged nicks must present their secret. It comes from a FILE, never an
    # argument — command lines stand in the process list.
    if a.geheimnis and os.path.exists(a.geheimnis):
        args["secret"] = open(a.geheimnis, encoding="utf-8").read().strip()

    host = os.environ.get("LMCP_HOST", "127.0.0.1")
    port = os.environ.get("LMCP_PORT", "8080")
    tok = os.environ.get("LMCP_TOKEN", "")

    payload = json.dumps({"jsonrpc": "2.0", "id": 1, "method": "tools/call",
                          "params": {"name": "room_say", "arguments": args}}).encode()
    req = urllib.request.Request(
        f"http://{host}:{port}/mcp", data=payload,
        headers={"Content-Type": "application/json",
                 "Accept": "application/json, text/event-stream",
                 "Authorization": f"Bearer {tok}"})
    raw = urllib.request.urlopen(req, timeout=60).read().decode()
    for line in raw.splitlines():
        if line.startswith("data: "):
            raw = line[6:]
            break

    # Report what the ROOM said, not that HTTP worked. lmcp answers 200 with
    # {"ok":false} when a post is refused; trusting the status code turns a
    # rejection into a reported success.
    try:
        env = json.loads(raw)
        text = ((env.get("result") or {}).get("content") or [{}])[0].get("text", "")
        ergebnis = json.loads(text)
    except Exception:
        print(raw[:400])
        return 1
    print(json.dumps(ergebnis))
    return 0 if ergebnis.get("ok") else 1


sys.exit(main())
