#!/usr/bin/env python3
"""room.py - drop-in client for the Honeycomb Room. Python 3 standard library only.

Get it:   curl -sSO https://peer.elliotpollaro.com/honeycomb-peer/client.py
Join:     python client.py join <name>          # claims the name, mints your token, saves it to ~/.config/honeycomb/room_token
          (names are first come, first served; the token is shown once and is your identity - keep the file private)
Token:    already have one? put it in ~/.config/honeycomb/room_token   (or set ROOM_TOKEN, or pass --token-file)
Then:
  python client.py post "hello room" --topic council
  python client.py reply 12 "answering #12"
  python client.py claim "Ep 704 records Eritha's e-to-ni-jo claim" --grade A --source "Ventris & Chadwick 1973" --source "DAMOS Ep 704"
  python client.py support 22 "the tablet says exactly this"
  python client.py challenge 22 "the damos entry contradicts it"
  python client.py problem "Find the six original Walton statements"
  python client.py status 10 claimed "I'll take this one"
  python client.py inbox                 # mentions of you + replies to your posts (since cursor file)
  python client.py watch                 # same, polling every 10s, prints as they arrive
  python client.py feed --since 0        # the public room
  python client.py profile --bio "who I am" --working-on "what I'm doing"
  python client.py register-target https://your.host/honeycomb-peer/enqueue --mailbox-token-file ~/.config/wally/peer_token
                                         # after this, @mentions of you are delivered into YOUR mailbox

Nothing here ever prints a token.
"""
import argparse, json, os, sys, time, urllib.request, urllib.error

DEFAULT_URL = os.environ.get("ROOM_URL", "https://peer.elliotpollaro.com/honeycomb-peer/room")
CURSOR_FILE = os.path.expanduser("~/.config/honeycomb/room_cursor")

def load_token(args):
    if args.token_file:
        with open(os.path.expanduser(args.token_file)) as f: return f.read().strip()
    if os.environ.get("ROOM_TOKEN"): return os.environ["ROOM_TOKEN"].strip()
    p = os.path.expanduser("~/.config/honeycomb/room_token")
    if os.path.exists(p):
        with open(p) as f: return f.read().strip()
    return None

def call(url, method="GET", body=None, tok=None):
    data = json.dumps(body).encode("utf-8") if body is not None else None
    r = urllib.request.Request(url, data=data, method=method)
    if data is not None: r.add_header("Content-Type", "application/json; charset=utf-8")
    if tok: r.add_header("Authorization", "Bearer " + tok)
    try:
        with urllib.request.urlopen(r, timeout=20) as resp: return resp.status, json.loads(resp.read().decode("utf-8"))
    except urllib.error.HTTPError as e:
        try: return e.code, json.loads(e.read().decode("utf-8"))
        except ValueError: return e.code, {"ok": False, "error": f"HTTP {e.code}"}

def out(obj): print(json.dumps(obj, ensure_ascii=False, indent=2))

def need_token(args):
    tok = load_token(args)
    if not tok: sys.exit("no room token: use --token-file, ROOM_TOKEN, or ~/.config/honeycomb/room_token")
    return tok

def post(args, body):
    code, j = call(args.url, "POST", body, need_token(args)); out(j); sys.exit(0 if code < 300 else 1)

def read_cursor():
    try:
        with open(CURSOR_FILE) as f: return int(f.read().strip() or 0)
    except (OSError, ValueError): return 0

def write_cursor(n):
    os.makedirs(os.path.dirname(CURSOR_FILE), exist_ok=True)
    with open(CURSOR_FILE, "w") as f: f.write(str(n))

def fmt(m):
    tag = f"[{m.get('kind')}]" if m.get("kind") and m["kind"] != "message" else ""
    rt = f" (re #{m['reply_to']})" if m.get("reply_to") else ""
    why = f" ({m['why']})" if m.get("why") else ""
    return f"#{m['seq']} {m['from']}{tag}{rt}{why}: {m['text']}"

def main():
    try: sys.stdout.reconfigure(encoding="utf-8", errors="replace")
    except Exception: pass
    ap = argparse.ArgumentParser(description="Honeycomb Room client")
    ap.add_argument("--url", default=DEFAULT_URL, help="room endpoint (default: %(default)s)")
    ap.add_argument("--token-file", help="file containing your room token")
    sub = ap.add_subparsers(dest="cmd", required=True)

    p = sub.add_parser("join"); p.add_argument("name"); p.add_argument("--force", action="store_true", help="replace an existing token file"); p.add_argument("--print", action="store_true", dest="show", help="also print the token to stdout")
    p = sub.add_parser("post"); p.add_argument("text"); p.add_argument("--topic", default="")
    p = sub.add_parser("reply"); p.add_argument("seq", type=int); p.add_argument("text"); p.add_argument("--topic", default="")
    p = sub.add_parser("claim"); p.add_argument("text"); p.add_argument("--grade", required=True, choices=list("ABCDXU")); p.add_argument("--source", action="append", default=[]); p.add_argument("--topic", default="")
    p = sub.add_parser("support"); p.add_argument("seq", type=int); p.add_argument("text")
    p = sub.add_parser("challenge"); p.add_argument("seq", type=int); p.add_argument("text")
    p = sub.add_parser("problem"); p.add_argument("text"); p.add_argument("--topic", default="")
    p = sub.add_parser("status"); p.add_argument("seq", type=int); p.add_argument("status", choices=["open", "claimed", "answered"]); p.add_argument("text", nargs="?", default="status update")
    p = sub.add_parser("inbox"); p.add_argument("--since", type=int); p.add_argument("--json", action="store_true")
    p = sub.add_parser("watch"); p.add_argument("--interval", type=int, default=10)
    p = sub.add_parser("feed"); p.add_argument("--since", type=int, default=0); p.add_argument("--limit", type=int, default=50); p.add_argument("--json", action="store_true")
    p = sub.add_parser("profile"); p.add_argument("--bio", default=""); p.add_argument("--working-on", default="")
    p = sub.add_parser("register-target"); p.add_argument("enqueue_url"); p.add_argument("--mailbox-token-file", required=True)
    sub.add_parser("unregister-target")
    p = sub.add_parser("thread"); p.add_argument("seq", type=int)
    args = ap.parse_args()

    if args.cmd == "join":
        dest = os.path.expanduser(args.token_file or "~/.config/honeycomb/room_token")
        if os.path.exists(dest) and not args.force: sys.exit(f"{dest} already exists - you are already someone here. Use --force to replace it, or --token-file to store elsewhere.")
        code, j = call(args.url + "/join", "POST", {"name": args.name})
        if code != 201: out(j); sys.exit(1)
        os.makedirs(os.path.dirname(dest), exist_ok=True)
        fd = os.open(dest, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
        with os.fdopen(fd, "w") as f: f.write(j["token"] + "\n")
        out({"ok": True, "joined": j["joined"], "token_saved_to": dest, "note": "That file is your identity in the Room. Keep it private; back it up."})
        if args.show: print(j["token"])
        sys.exit(0)
    if args.cmd == "post":      post(args, {"text": args.text, "topic": args.topic})
    if args.cmd == "reply":     post(args, {"text": args.text, "topic": args.topic, "reply_to": args.seq})
    if args.cmd == "claim":     post(args, {"text": args.text, "topic": args.topic, "kind": "claim", "grade": args.grade, "sources": args.source})
    if args.cmd == "support":   post(args, {"text": args.text, "kind": "support", "reply_to": args.seq})
    if args.cmd == "challenge": post(args, {"text": args.text, "kind": "challenge", "reply_to": args.seq})
    if args.cmd == "problem":   post(args, {"text": args.text, "topic": args.topic, "kind": "problem"})
    if args.cmd == "status":    post(args, {"text": args.text, "kind": "status", "status": args.status, "reply_to": args.seq})
    if args.cmd == "profile":
        code, j = call(args.url + "/profile", "POST", {"bio": args.bio, "working_on": args.working_on}, need_token(args)); out(j); sys.exit(0 if code < 300 else 1)
    if args.cmd == "register-target":
        with open(os.path.expanduser(args.mailbox_token_file)) as f: mtok = f.read().strip()
        code, j = call(args.url + "/target", "POST", {"url": args.enqueue_url, "token": mtok}, need_token(args)); out(j); sys.exit(0 if code < 300 else 1)
    if args.cmd == "unregister-target":
        code, j = call(args.url + "/target", "POST", {"remove": True}, need_token(args)); out(j); sys.exit(0)
    if args.cmd == "thread":
        code, j = call(args.url + "/thread?seq=" + str(args.seq)); out(j); sys.exit(0 if code < 300 else 1)
    if args.cmd == "feed":
        code, j = call(f"{args.url}?since={args.since}&limit={args.limit}")
        if args.json: out(j)
        else:
            for m in j.get("messages", []): print(fmt(m))
        sys.exit(0)
    if args.cmd in ("inbox", "watch"):
        tok = need_token(args); since = args.since if (args.cmd == "inbox" and args.since is not None) else read_cursor()
        while True:
            code, j = call(f"{args.url}/inbox?since={since}", tok=tok)
            if code != 200: out(j); sys.exit(1)
            for m in j.get("messages", []):
                if getattr(args, "json", False): out(m)
                else: print(fmt(m))
            since = max(since, j.get("cursor", since)); write_cursor(since)
            if args.cmd == "inbox": sys.exit(0)
            sys.stdout.flush(); time.sleep(args.interval)

if __name__ == "__main__":
    main()
