#!/usr/bin/env python3
"""mx - Matrix bridge for the Claude coordinator session.

  mx setup HOMESERVER OWNER     log in bot, create room, invite owner (once)
                                e.g. mx setup https://matrix.example.internal @deinname:matrix.example.internal
  mx send [-f FILE] [TEXT...]   send markdown message to the room (stdin if no text)
  mx listen                     stream incoming messages + session events as JSON lines
  mx event                      hook entry point (Stop / PermissionRequest), reads stdin
  mx watch [add|rm|list|clear] [PANE...]   panes whose events reach the coordinator
  mx coordinator-pane [PANE]    remember/show the coordinator's own pane

Files:
  ~/.config/koordinator/koordinator.pw   bot password (only needed for setup)
  ~/.config/koordinator/matrix.json      written by setup: homeserver, owner, bot token, room
  ~/.config/koordinator/deepgram-key     optional: Deepgram API key to transcribe voice messages
  ~/.config/koordinator/begriffe.txt     optional: terms that help the transcription, one per line
  ~/.local/state/koordinator/            sync token, event queue, watched panes, outbox
"""
import fcntl
import json
import os
import subprocess
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
from pathlib import Path

CONF_DIR = Path("~/.config/koordinator").expanduser()
CONF = CONF_DIR / "matrix.json"
STATE = Path("~/.local/state/koordinator").expanduser()
EVENTS = STATE / "events.jsonl"
OFFSET = STATE / "events.offset"
SINCE = STATE / "since"
WATCH = STATE / "watch.json"
COORD = STATE / "coordinator-pane"
MEDIA = STATE / "media"
OUTBOX = STATE / "outbox.jsonl"
TERMS = CONF_DIR / "begriffe.txt"
DEEPGRAM_KEY = CONF_DIR / "deepgram-key"
BOT = os.environ.get("MX_BOT", "koordinator")
EXCERPT = 2500


def load_conf():
    return json.loads(CONF.read_text())


def api(conf, method, path, body=None, params=None, raw=None, ctype=None, timeout=60):
    url = conf["homeserver"] + path
    if params:
        url += "?" + urllib.parse.urlencode(params)
    data = raw if raw is not None else (json.dumps(body).encode() if body is not None else None)
    req = urllib.request.Request(url, data=data, method=method)
    if conf.get("token"):
        req.add_header("Authorization", "Bearer " + conf["token"])
    if data is not None:
        req.add_header("Content-Type", ctype or "application/json")
    with urllib.request.urlopen(req, timeout=timeout) as r:
        payload = r.read()
    return payload if raw is not None or path.startswith("/_matrix/client/v1/media") else json.loads(payload or b"{}")


def q(s):
    return urllib.parse.quote(s, safe="")


def cmd_setup(args):
    if len(args) != 2 or not args[1].startswith("@"):
        sys.exit("mx setup HOMESERVER OWNER   e.g. mx setup https://matrix.example.internal @deinname:matrix.example.internal")
    pw = (CONF_DIR / "koordinator.pw").read_text().strip()
    conf = {"homeserver": args[0].rstrip("/"), "owner": args[1]}
    r = api(conf, "POST", "/_matrix/client/v3/login", {
        "type": "m.login.password",
        "identifier": {"type": "m.id.user", "user": BOT},
        "password": pw,
        "device_id": "KOORDINATOR",
        "initial_device_display_name": "koordinator",
    })
    conf.update(user=r["user_id"], token=r["access_token"])
    room = api(conf, "POST", "/_matrix/client/v3/createRoom", {
        "preset": "trusted_private_chat",
        "name": "Koordinator",
        "topic": "Claude-Sessions steuern",
        "invite": [conf["owner"]],
        "is_direct": True,
    })
    conf["room"] = room["room_id"]
    api(conf, "PUT", f"/_matrix/client/v3/profile/{q(conf['user'])}/displayname", {"displayname": "Koordinator"})
    CONF_DIR.mkdir(parents=True, exist_ok=True)
    CONF.write_text(json.dumps(conf, indent=1))
    CONF.chmod(0o600)
    print("ok", conf["user"], conf["room"])


def to_html(text):
    try:
        import markdown
    except ImportError:
        import html
        return html.escape(text).replace("\n", "<br>")
    return markdown.markdown(text, extensions=["fenced_code", "nl2br", "sane_lists", "tables"])


def send_event(conf, content):
    txn = uuid.uuid4().hex
    return api(conf, "PUT", f"/_matrix/client/v3/rooms/{q(conf['room'])}/send/m.room.message/{txn}", content)


def cmd_send(args):
    if args[:1] == ["-f"]:
        text = Path(args[1]).read_text()
    elif args:
        text = " ".join(args)
    else:
        text = sys.stdin.read()
    text = text.strip()
    if not text:
        sys.exit("mx send: leerer Text")
    deliver({"art": "text", "text": text})


def do_text(conf, text):
    if len(text) > 30000:
        text = text[:30000] + "\n\n… (gekürzt)"
    r = send_event(conf, {"msgtype": "m.text", "body": text, "format": "org.matrix.custom.html",
                          "formatted_body": to_html(text)})
    return f"gesendet {r.get('event_id', '')}".strip()


def do_item(conf, item):
    return do_text(conf, item["text"])


def matrix_down(e):
    return isinstance(e, (urllib.error.URLError, TimeoutError, OSError)) and not (
        isinstance(e, urllib.error.HTTPError) and e.code < 500)


def deliver(item):
    conf = load_conf()
    try:
        print(do_item(conf, item))
    except Exception as e:
        if not matrix_down(e):
            raise
        STATE.mkdir(parents=True, exist_ok=True)
        item["zeit"] = time.strftime("%H:%M")
        with OUTBOX.open("a") as f:
            f.write(json.dumps(item, ensure_ascii=False) + "\n")
        print(f"Matrix nicht erreichbar ({e}). Vorgemerkt, wird automatisch zugestellt, sobald die Verbindung steht.")


def flush_outbox(conf):
    if not OUTBOX.exists() or not OUTBOX.stat().st_size:
        return 0
    items = [json.loads(l) for l in OUTBOX.read_text().splitlines() if l.strip()]
    rest = []
    for i, item in enumerate(items):
        try:
            if i == 0:
                do_text(conf, f"_Nachgereicht, Matrix war nicht erreichbar ({len(items)} Nachrichten):_")
            item["text"] = f"[{item.get('zeit', '')}] {item['text']}"
            do_item(conf, item)
        except Exception:
            rest = items[i:]
            break
    OUTBOX.write_text("".join(json.dumps(x, ensure_ascii=False) + "\n" for x in rest))
    return len(items) - len(rest)


def desktop_notify(text):
    try:
        subprocess.run(["notify-send", "-u", "normal", "Koordinator", text], timeout=5)
    except Exception:
        pass


def emit(obj):
    sys.stdout.write(json.dumps(obj, ensure_ascii=False) + "\n")
    sys.stdout.flush()


def download(conf, mxc):
    server, media_id = mxc[len("mxc://"):].split("/", 1)
    return api(conf, "GET", f"/_matrix/client/v1/media/download/{q(server)}/{q(media_id)}", timeout=120)


def keyterms(limit=30):
    terms = []
    try:
        terms += [l.strip() for l in TERMS.read_text().splitlines() if l.strip() and not l.startswith("#")]
    except OSError:
        pass
    try:
        out = subprocess.run(["tmux", "list-windows", "-a", "-F", "#{window_name}"],
                             capture_output=True, text=True, timeout=3).stdout
        skip = {"claude", "zsh", "bash", "koordinator"}
        terms += [w.replace("-", " ") for w in out.split() if len(w) > 2 and w not in skip][:10]
    except Exception:
        pass
    seen, out = set(), []
    for t in terms:
        if t.lower() not in seen:
            seen.add(t.lower())
            out.append(t)
    return out[:limit]


def transcribe(audio, mimetype):
    key = DEEPGRAM_KEY.read_text().strip()
    params = [("model", "nova-3"), ("language", "de"), ("smart_format", "true")]
    params += [("keyterm", t) for t in keyterms()]
    url = "https://api.deepgram.com/v1/listen?" + urllib.parse.urlencode(params)
    req = urllib.request.Request(url, data=audio, method="POST")
    req.add_header("Authorization", "Token " + key)
    req.add_header("Content-Type", mimetype or "audio/ogg")
    with urllib.request.urlopen(req, timeout=120) as r:
        res = json.load(r)
    alt = res["results"]["channels"][0]["alternatives"][0]
    unsure = [w.get("punctuated_word", w["word"]) for w in alt.get("words", []) if w.get("confidence", 1) < 0.6]
    return alt["transcript"], unsure


def handle_message(conf, ev):
    c = ev.get("content", {})
    t = c.get("msgtype")
    when = time.strftime("%H:%M", time.localtime(ev.get("origin_server_ts", 0) / 1000))
    if t in ("m.text", "m.notice", "m.emote"):
        return {"typ": "nachricht", "zeit": when, "text": c.get("body", "")}
    if t == "m.audio":
        if not DEEPGRAM_KEY.exists():
            return {"typ": "sprachnachricht", "zeit": when,
                    "fehler": "Sprachnachricht erhalten, aber keine Transkription eingerichtet (deepgram-key fehlt)."}
        try:
            text, unsure = transcribe(download(conf, c["url"]), c.get("info", {}).get("mimetype"))
            out = {"typ": "sprachnachricht", "zeit": when, "text": text or "(nichts erkannt)"}
            if unsure:
                out["unsicher"] = unsure
            return out
        except Exception as e:
            return {"typ": "sprachnachricht", "zeit": when, "fehler": f"Transkription fehlgeschlagen: {e}"}
    if t in ("m.image", "m.file", "m.video") and c.get("url"):
        MEDIA.mkdir(parents=True, exist_ok=True)
        name = os.path.basename(c.get("filename") or c.get("body") or "datei")
        path = MEDIA / f"{int(time.time())}-{name}"
        try:
            path.write_bytes(download(conf, c["url"]))
            return {"typ": t[2:], "zeit": when, "pfad": str(path), "text": c.get("body", "")}
        except Exception as e:
            return {"typ": t[2:], "zeit": when, "fehler": f"Download fehlgeschlagen: {e}"}
    return None


def fetch_event(conf, event_id):
    return api(conf, "GET", f"/_matrix/client/v3/rooms/{q(conf['room'])}/event/{q(event_id)}")


def handle_reaction(conf, ev, fetch=fetch_event):
    rel = ev.get("content", {}).get("m.relates_to", {})
    if rel.get("rel_type") != "m.annotation" or not rel.get("event_id"):
        return None
    when = time.strftime("%H:%M", time.localtime(ev.get("origin_server_ts", 0) / 1000))
    out = {"typ": "reaktion", "zeit": when, "emoji": rel.get("key", ""), "bezug_id": rel["event_id"]}
    try:
        target = fetch(conf, rel["event_id"])
        c = target.get("content", {})
        text = c.get("body", "")
        if c.get("msgtype") == "m.audio":
            text = "(Sprachnachricht)"
        out["bezug"] = text if len(text) <= 300 else text[:300] + " …"
        out["bezug_von"] = "koordinator" if target.get("sender") == conf["user"] else "nutzer"
    except Exception as e:
        out["bezug"] = f"(nicht auflösbar: {e})"
    return out


def ack(conf, event_id):
    try:
        api(conf, "POST", f"/_matrix/client/v3/rooms/{q(conf['room'])}/receipt/m.read/{q(event_id)}", {})
        api(conf, "PUT", f"/_matrix/client/v3/rooms/{q(conf['room'])}/typing/{q(conf['user'])}",
            {"typing": True, "timeout": 60000})
    except Exception:
        pass


def drain_events():
    if not EVENTS.exists():
        return
    off = int(OFFSET.read_text()) if OFFSET.exists() else 0
    size = EVENTS.stat().st_size
    if size < off:
        off = 0
    if size == off:
        return
    with EVENTS.open() as f:
        f.seek(off)
        for line in f:
            if line.strip():
                sys.stdout.write(line if line.endswith("\n") else line + "\n")
        off = f.tell()
    sys.stdout.flush()
    OFFSET.write_text(str(off))
    if off > 1_000_000:
        EVENTS.write_text("")
        OFFSET.write_text("0")


def cmd_listen(_):
    STATE.mkdir(parents=True, exist_ok=True)
    lock = open(STATE / "listen.lock", "w")
    try:
        fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except BlockingIOError:
        sys.exit("mx listen läuft schon")
    conf = load_conf()
    filt = json.dumps({"room": {"rooms": [conf["room"]], "timeline": {"limit": 50},
                                "state": {"lazy_load_members": True}},
                       "presence": {"types": []}, "account_data": {"types": []}})
    since = SINCE.read_text().strip() if SINCE.exists() else None
    down_since = None
    while True:
        drain_events()
        params = {"filter": filt, "timeout": 15000}
        if since:
            params["since"] = since
        try:
            r = api(conf, "GET", "/_matrix/client/v3/sync", params=params, timeout=40)
        except (urllib.error.URLError, TimeoutError, OSError) as e:
            if down_since is None:
                down_since = time.time()
            elif time.time() - down_since > 120 and down_since > 0:
                emit({"typ": "stoerung", "text": f"Matrix nicht erreichbar ({e}). Antworten werden vorgemerkt."})
                desktop_notify("Matrix nicht erreichbar: Handy-Nachrichten kommen nicht an, Antworten werden vorgemerkt.")
                down_since = -1
            time.sleep(5)
            continue
        if down_since == -1:
            n = flush_outbox(conf)
            emit({"typ": "stoerung", "text": f"Matrix wieder erreichbar, {n} vorgemerkte Nachrichten zugestellt."})
            desktop_notify("Matrix wieder erreichbar.")
        elif OUTBOX.exists() and OUTBOX.stat().st_size:
            flush_outbox(conf)
        down_since = None
        rooms = r.get("rooms", {})
        if since:
            for room_id in rooms.get("invite", {}):
                if room_id != conf["room"]:
                    api(conf, "POST", f"/_matrix/client/v3/rooms/{q(room_id)}/leave", {})
            joined = rooms.get("join", {}).get(conf["room"], {})
            for ev in joined.get("timeline", {}).get("events", []):
                if ev.get("sender") != conf["owner"]:
                    continue
                if ev.get("type") == "m.reaction":
                    out = handle_reaction(conf, ev)
                    if out:
                        emit(out)
                        ack(conf, ev["event_id"])
                    continue
                if ev.get("type") != "m.room.message":
                    continue
                if "m.relates_to" in ev.get("content", {}) and ev["content"]["m.relates_to"].get("rel_type") == "m.replace":
                    continue
                out = handle_message(conf, ev)
                if out:
                    emit(out)
                    ack(conf, ev["event_id"])
        since = r["next_batch"]
        SINCE.write_text(since)


def read_watch():
    try:
        return set(json.loads(WATCH.read_text()))
    except Exception:
        return set()


def cmd_watch(args):
    STATE.mkdir(parents=True, exist_ok=True)
    sub, panes = (args[0], args[1:]) if args else ("list", [])
    w = read_watch()
    if sub == "add":
        w |= set(panes)
    elif sub == "rm":
        w -= set(panes)
    elif sub == "clear":
        w = set()
    elif sub != "list":
        sys.exit("mx watch [add|rm|list|clear] [PANE...]")
    WATCH.write_text(json.dumps(sorted(w)))
    for p in sorted(w):
        print(p, tmux_name(p))


def cmd_coordinator_pane(args):
    STATE.mkdir(parents=True, exist_ok=True)
    if args:
        COORD.write_text(args[0])
    print(COORD.read_text() if COORD.exists() else "")


def tmux_name(pane):
    try:
        return subprocess.run(["tmux", "display-message", "-p", "-t", pane, "#{session_name}:#{window_name}"],
                              capture_output=True, text=True, timeout=3).stdout.strip()
    except Exception:
        return ""


def last_assistant_text(transcript):
    try:
        with open(transcript, "rb") as f:
            f.seek(0, 2)
            f.seek(max(0, f.tell() - 400_000))
            lines = f.read().decode("utf-8", "ignore").splitlines()
    except Exception:
        return ""
    for line in reversed(lines):
        try:
            d = json.loads(line)
        except Exception:
            continue
        if d.get("type") != "assistant":
            continue
        parts = [c.get("text", "") for c in d.get("message", {}).get("content", []) if c.get("type") == "text"]
        if any(p.strip() for p in parts):
            return "\n".join(parts).strip()
    return ""


def cmd_event(_):
    try:
        data = json.load(sys.stdin)
    except Exception:
        return
    pane = os.environ.get("TMUX_PANE", "")
    if not pane or pane not in read_watch():
        return
    if COORD.exists() and COORD.read_text().strip() == pane:
        return
    hook = data.get("hook_event_name", "")
    out = {"typ": "session", "pane": pane, "fenster": tmux_name(pane), "ordner": data.get("cwd", ""),
           "zeit": time.strftime("%H:%M")}
    if hook == "Stop":
        text = data.get("last_assistant_message") or last_assistant_text(data.get("transcript_path", ""))
        if len(text) > EXCERPT:
            text = "…" + text[-EXCERPT:]
        out.update(art="fertig", antwort=text)
    elif hook == "PermissionRequest":
        detail = json.dumps(data.get("tool_input", {}), ensure_ascii=False)
        out.update(art="freigabe", tool=data.get("tool_name", ""), detail=detail[:800])
    else:
        return
    STATE.mkdir(parents=True, exist_ok=True)
    with EVENTS.open("a") as f:
        fcntl.flock(f, fcntl.LOCK_EX)
        f.write(json.dumps(out, ensure_ascii=False) + "\n")


def main():
    cmds = {"setup": cmd_setup, "send": cmd_send, "listen": cmd_listen, "event": cmd_event,
            "watch": cmd_watch, "coordinator-pane": cmd_coordinator_pane}
    if len(sys.argv) < 2 or sys.argv[1] not in cmds:
        sys.exit(__doc__)
    cmds[sys.argv[1]](sys.argv[2:])


if __name__ == "__main__":
    main()
