#!/usr/bin/env python3
"""Pi menu: tray icon on the Pi desktop (labwc / wf-panel-pi).

Title shows CPU%% and temp. Menu shows vitals, hub reachability, and controls.
Hub URL: ~/.config/pi-menu/hub  (one line), else http://<default-gateway>:4040.
"""
from __future__ import annotations

import json
import os
import shutil
import socket
import subprocess
import urllib.error
import urllib.request

import gi

gi.require_version("Gtk", "3.0")
from gi.repository import GLib, Gtk  # noqa: E402

IND = None
for _ns in ("AyatanaAppIndicator3", "AppIndicator3"):
    try:
        gi.require_version(_ns, "0.1")
        IND = getattr(__import__("gi.repository", fromlist=[_ns]), _ns)
        break
    except Exception:
        pass

CFG = os.path.expanduser("~/.config/pi-menu/hub")
SERVICE_CANDIDATES = ("aether-agent", "aether7-pi")


def default_hub() -> str:
    try:
        out = subprocess.check_output(
            ["ip", "route", "show", "default"], text=True, stderr=subprocess.DEVNULL
        )
        parts = out.split()
        if "via" in parts:
            gw = parts[parts.index("via") + 1]
            if gw:
                return f"http://{gw}:4040"
    except Exception:
        pass
    return "http://localhost:4040"


HUB = open(CFG).read().strip() if os.path.exists(CFG) else default_hub()


def service_name() -> str:
    for name in SERVICE_CANDIDATES:
        try:
            r = subprocess.run(
                ["systemctl", "is-enabled", name],
                capture_output=True,
                text=True,
                timeout=2,
            )
            if r.returncode == 0 or "enabled" in (r.stdout + r.stderr):
                return name
        except Exception:
            pass
    return SERVICE_CANDIDATES[0]


SERVICE = service_name()


def sh(cmd: str, terminal: bool = False) -> None:
    if terminal:
        term = (
            shutil.which("lxterminal")
            or shutil.which("x-terminal-emulator")
            or shutil.which("gnome-terminal")
        )
        if term:
            wrapped = cmd + '; echo; read -p "done - enter" _'
            cmd = f"{term} -e bash -c {json.dumps(wrapped)}"
    subprocess.Popen(cmd, shell=True)


def local_vitals() -> dict:
    pi: dict = {}
    try:
        t = float(open("/sys/class/thermal/thermal_zone0/temp").read()) / 1000
        pi["temperatureC"] = round(t, 1)
    except Exception:
        pass
    try:
        # first line of /proc/loadavg is a rough stand-in when hub is closed
        load = float(open("/proc/loadavg").read().split()[0])
        pi["cpuUsagePercent"] = round(min(100.0, load * 25), 1)
    except Exception:
        pass
    try:
        mem = open("/proc/meminfo").read()
        vals = {}
        for line in mem.splitlines():
            k, v, *_ = line.replace(":", " ").split()
            if k in ("MemTotal", "MemAvailable"):
                vals[k] = int(v)
        if "MemTotal" in vals and "MemAvailable" in vals:
            total = vals["MemTotal"] / (1024 * 1024)
            used = (vals["MemTotal"] - vals["MemAvailable"]) / (1024 * 1024)
            pi["memory"] = {
                "totalGB": round(total, 1),
                "usedGB": round(used, 1),
            }
    except Exception:
        pass
    return pi


def vitals():
    pi, hub_ok = {}, False
    try:
        req = urllib.request.Request(
            HUB.rstrip("/") + "/api/status",
            headers={"User-Agent": "pi-menu/1.0", "Accept": "application/json"},
        )
        with urllib.request.urlopen(req, timeout=3) as r:
            d = json.load(r)
        pi = d.get("pi") or {}
        hub_ok = True
        if isinstance(d.get("server"), dict) and "piConnected" in d["server"]:
            # keep a flag for the hub row
            pi = dict(pi, _hubPiConnected=d["server"]["piConnected"])
    except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, socket.timeout, ValueError):
        pass
    if not pi.get("temperatureC") or not hub_ok:
        local = local_vitals()
        for k, v in local.items():
            pi.setdefault(k, v)
    return pi, hub_ok


class App:
    def __init__(self):
        self.menu = Gtk.Menu()
        self.items = {}
        for key in ("cpu", "temp", "mem", "npu", "hub"):
            it = Gtk.MenuItem(label=key)
            it.set_sensitive(False)
            self.menu.append(it)
            self.items[key] = it
        self.menu.append(Gtk.SeparatorMenuItem())
        actions = [
            ("Open deck (browser)", lambda *_: sh(
                f"chromium-browser --new-window {HUB} || chromium --new-window {HUB} || xdg-open {HUB}"
            )),
            ("Restart vitals collector", lambda *_: sh(f"sudo systemctl restart {SERVICE}")),
            ("Collector status", lambda *_: sh(
                f"systemctl status {SERVICE} --no-pager -l; echo; journalctl -u {SERVICE} -n 40 --no-pager",
                True,
            )),
            ("Start Ollama", lambda *_: sh("sudo systemctl start ollama")),
            ("Stop Ollama", lambda *_: sh("sudo systemctl stop ollama")),
            ("Pull qwen2.5:0.5b", lambda *_: sh("ollama pull qwen2.5:0.5b", True)),
            ("Open terminal", lambda *_: sh("lxterminal || x-terminal-emulator || xdg-terminal")),
            ("Reboot Pi", lambda *_: self.confirm("Reboot the Pi?", "sudo reboot")),
            ("Shut down Pi", lambda *_: self.confirm("Shut down the Pi?", "sudo poweroff")),
            ("Quit menu", lambda *_: Gtk.main_quit()),
        ]
        for label, fn in actions:
            it = Gtk.MenuItem(label=label)
            it.connect("activate", fn)
            self.menu.append(it)
        self.menu.show_all()

        if IND:
            self.ind = IND.Indicator.new(
                "pi-menu", "computer-symbolic", IND.IndicatorCategory.SYSTEM_SERVICES
            )
            self.ind.set_status(IND.IndicatorStatus.ACTIVE)
            self.ind.set_menu(self.menu)
            self.icon = None
        else:
            self.ind = None
            self.icon = Gtk.StatusIcon.new_from_icon_name("computer")
            self.icon.connect(
                "popup-menu",
                lambda i, b, t: self.menu.popup(
                    None, None, Gtk.StatusIcon.position_menu, i, b, t
                ),
            )
            self.icon.connect(
                "activate",
                lambda i: self.menu.popup(
                    None, None, Gtk.StatusIcon.position_menu, i, 1, Gtk.get_current_event_time()
                ),
            )
        self.tick()
        GLib.timeout_add_seconds(3, self.tick)

    def confirm(self, text, cmd):
        d = Gtk.MessageDialog(
            message_type=Gtk.MessageType.QUESTION,
            buttons=Gtk.ButtonsType.OK_CANCEL,
            text=text,
        )
        if d.run() == Gtk.ResponseType.OK:
            sh(cmd)
        d.destroy()

    def tick(self):
        pi, ok = vitals()
        n = lambda v, u="": f"{round(v)}{u}" if isinstance(v, (int, float)) else "-"
        cpu, temp = pi.get("cpuUsagePercent"), pi.get("temperatureC")
        mem = pi.get("memory") or {}
        acc = ((pi.get("ai") or {}).get("accelerators") or [{}])[0]
        throttled = (pi.get("throttling") or {}).get("isThrottled")
        self.items["cpu"].set_label(f"CPU  {n(cpu, '%')}   {n(pi.get('cpuFreqMHz'), ' MHz')}")
        self.items["temp"].set_label(
            f"Temp  {n(temp, '°C')}   {'throttled!' if throttled else 'ok'}"
        )
        self.items["mem"].set_label(f"RAM  {mem.get('usedGB', '-')} / {mem.get('totalGB', '-')} GB")
        tops = acc.get("tops") or ""
        self.items["npu"].set_label(f"NPU  {acc.get('name', 'none')}  {tops}".rstrip())
        self.items["hub"].set_label(f"Hub  {'connected' if ok else 'unreachable'}  ({HUB})")
        title = f"{n(cpu, '%')} {n(temp, '°')}"
        if self.ind:
            self.ind.set_label(title, "99% 99°")
        elif self.icon:
            self.icon.set_tooltip_text("Pi " + title)
        return True


if __name__ == "__main__":
    App()
    Gtk.main()
