#!/usr/bin/python3
# Zikporx LLM Gateway, the Linux desktop app (2026-11-27).
#
# The same small window the Mac (Swift) and Windows (C#) apps have: it runs the bundled launcher
# (`node main.js open --print`), which makes sure the gateway runs as this user's own background
# service (systemd --user, see src/service.ts) and prints the page address; the page is shown in
# a WebKitGTK window. A tray icon (Ayatana AppIndicator) stays while the window is closed.
#
#   zikporx-llm-gateway               open the window
#   zikporx-llm-gateway --background  started at login: only the tray icon
#
# Installed by the .deb into /opt/zikporx-llm-gateway (scripts/package-linux-deb.sh). The command
# install (install.sh, a system service in /opt/zikporx-gateway) is separate and stays as it is.
import os
import subprocess
import sys
import threading
import urllib.request

import gi

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

try:
    gi.require_version("AyatanaAppIndicator3", "0.1")
    from gi.repository import AyatanaAppIndicator3 as AppIndicator  # noqa: E402
except (ValueError, ImportError):
    AppIndicator = None

NAME = "Zikporx LLM Gateway"
APP_ID = "com.zikporx.gateway.app"
ROOT = os.path.dirname(os.path.realpath(__file__))
NODE = os.path.join(ROOT, "runtime", "node")
MAIN = os.path.join(ROOT, "app", "dist", "main.js")
ICON = os.path.join(ROOT, "icon.png")
DATA = os.environ.get("XDG_DATA_HOME") or os.path.expanduser("~/.local/share")
HOME = os.environ.get("ZIKPORX_HOME") or os.path.join(DATA, "zikporx-gateway")
CONFIG = os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser("~/.config")
AUTOSTART = os.path.join(CONFIG, "autostart", "zikporx-llm-gateway.desktop")
SYSTEM_SERVICE = "/etc/systemd/system/zikporx-gateway.service"   # the command install
NAVY = "#0b1222"


def open_link(url):
    """Open a web link in the user's browser. Through the desktop portal first: Ubuntu's Firefox is a snap,
    and a snap cannot start from a process with no_new_privs (WebKit's), which made links do nothing in
    Zikporx AI on Linux (fixed there in 1.2.42)."""
    try:
        subprocess.run(["gdbus", "call", "--session", "--dest", "org.freedesktop.portal.Desktop",
                        "--object-path", "/org/freedesktop/portal/desktop",
                        "--method", "org.freedesktop.portal.OpenURI.OpenURI", "", url, "{}"],
                       check=True, timeout=10, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    except Exception:
        try:
            subprocess.Popen(["xdg-open", url], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        except Exception:
            pass


def html_escape(text):
    return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace('"', "&quot;")


class GatewayApp(Gtk.Application):
    def __init__(self):
        # One copy only: Gtk.Application is unique per user session (D-Bus). A second start hands its
        # arguments to this one (do_command_line) and exits; the Mac app needed its own check (0.1.5).
        super().__init__(application_id=APP_ID, flags=Gio.ApplicationFlags.HANDLES_COMMAND_LINE)
        self.window = None
        self.web = None
        self.indicator = None
        self.state_item = None
        self.disconnect_item = None
        self.launcher = None
        self.page_url = None
        self.page_shown = False
        self.output = []
        self.pending_press = None
        self.started = False
        self.quitting = False
        self.health_tick = 0

    # ---- start-up ----

    def do_command_line(self, command_line):
        background = "--background" in command_line.get_arguments()[1:]
        if not self.started:
            self.started = True
            self.hold()   # stays alive with the window closed, while the tray icon is there
            self.build_window()
            self.build_tray()
            GLib.timeout_add_seconds(2, self.refresh_state)
            if os.path.exists(SYSTEM_SERVICE):
                # Installed with the command (install.sh): that gateway runs as a system service with its own data,
                # managed with `sudo zikporx`. Do not start a second one next to it.
                self.show_window()
                self.show_message(NAME + " is already installed on this computer",
                                  "It was installed with the command line and runs as a system service. Manage it with "
                                  "“sudo zikporx” (for example “sudo zikporx status”), or remove that "
                                  "install first with “sudo ./install.sh --uninstall” to use this app instead.",
                                  False)
                return 0
            self.keep_icon_at_login(True)
            if background and self.indicator is not None:
                return 0     # the service starts itself at login; the window opens from the tray
            self.show_window()   # also starts the launcher
        elif not background:
            self.show_window()
        return 0

    def build_window(self):
        self.window = Gtk.ApplicationWindow(application=self, title=NAME)
        self.window.set_default_size(760, 640)
        self.window.set_size_request(438, 480)
        self.window.set_position(Gtk.WindowPosition.CENTER)
        if os.path.exists(ICON):
            self.window.set_icon_from_file(ICON)
        settings = Gtk.Settings.get_default()
        if settings is not None:
            settings.set_property("gtk-application-prefer-dark-theme", True)
            # The desktop's own title bar buttons (Ubuntu: minimise, maximise, close). GTK does not always pick
            # them up by itself (only a close button showed on Ubuntu 24.04).
            layout = ":minimize,maximize,close"
            try:
                source = Gio.SettingsSchemaSource.get_default()
                if source is not None and source.lookup("org.gnome.desktop.wm.preferences", True) is not None:
                    layout = Gio.Settings.new("org.gnome.desktop.wm.preferences").get_string("button-layout") or layout
            except Exception:
                pass
            settings.set_property("gtk-decoration-layout", layout.replace("appmenu", "").replace("icon", ""))

        self.web = WebKit2.WebView()
        ws = self.web.get_settings()
        ws.set_user_agent(ws.get_user_agent() + " ZikporxLLMGatewayApp")
        ws.set_enable_developer_extras(False)
        ws.set_enable_write_console_messages_to_stdout(False)
        clear = Gdk.RGBA()
        clear.parse("rgba(0,0,0,0)")
        self.web.set_background_color(clear)   # the page's own rounded background shows through (style_window)
        self.web.connect("decide-policy", self.on_decide_policy)
        self.web.connect("load-changed", self.on_load_changed)
        self.web.connect("web-process-terminated", self.on_web_crashed)
        self.web.connect("script-dialog", self.on_script_dialog)
        self.web.connect("context-menu", self.on_context_menu)
        self.window.add(self.web)
        self.style_window()
        self.window.connect("delete-event", self.on_close)

    def style_window(self):
        """Title bar in the page's navy, and the window's bottom corners round like the top ones (2026-11-27).
        GTK 3 only rounds a window's top corners and cannot clip the page to the bottom ones, so the window is
        transparent and the page itself is drawn with rounded bottom corners (user style sheet below)."""
        header = Gtk.HeaderBar(title=NAME, show_close_button=True)
        header.get_style_context().add_class("zx-main")
        self.window.set_titlebar(header)
        self.window.get_style_context().add_class("zx-window")
        screen = self.window.get_screen()
        visual = screen.get_rgba_visual()
        if visual is not None and screen.is_composited():
            self.window.set_visual(visual)
            self.window.set_app_paintable(True)
            rounded = True
        else:
            rounded = False
        css = Gtk.CssProvider()
        css.load_from_data((
            "headerbar.zx-main { background: %(navy)s; background-image: none; border: none; box-shadow: none;"
            " color: #e8ecf6; border-radius: 12px 12px 0 0; }"
            "headerbar.zx-main .title { color: #e8ecf6; font-weight: bold; }"
            "headerbar.zx-main button { color: #cbd5e1; background: transparent; border: none; box-shadow: none; }"
            "headerbar.zx-main button:hover { background: rgba(255,255,255,0.10); }"
            "decoration { border-radius: 12px; }"
            "window.zx-window.background { background: %(bg)s; }"
            # The page's questions (Disconnect?, Stop and quit?): a gray title bar, gray body, all four corners round.
            "window.zx-dialog.background { background: #172033; border-radius: 0 0 12px 12px; }"
            "window.zx-dialog headerbar { background: #2a364a; background-image: none; border: none; box-shadow: none;"
            " color: #f1f5f9; border-radius: 12px 12px 0 0; min-height: 38px; }"
            "window.zx-dialog headerbar .title { color: #f1f5f9; font-weight: bold; }"
            "window.zx-dialog .zx-body { background: transparent; color: #e8ecf6; padding: 22px 24px 20px 24px; }"
            "window.zx-dialog .zx-body label { color: #e8ecf6; }"
            "window.zx-dialog .zx-body button { min-width: 90px; min-height: 30px; padding: 4px 14px; border-radius: 8px;"
            " background: #2a364a; color: #e8ecf6; border: none; box-shadow: none; }"
            "window.zx-dialog .zx-body button:hover { background: #354359; }"
            "window.zx-dialog .zx-body button.suggested-action { background: #3b82f6; color: #fff; border: none; }"
            % {"navy": NAVY, "bg": "transparent" if rounded else NAVY}).encode())
        Gtk.StyleContext.add_provider_for_screen(screen, css, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
        if rounded:
            page_css = (
                # The root keeps a (clear) background image so the body's background is not moved to the canvas,
                # which would fill the square corners again.
                "html{background:linear-gradient(transparent,transparent)!important;}"
                # The body is the scrolling box, exactly the window's height, so its round corners are always the
                # window's bottom corners (with the whole page scrolling they were below the fold).
                "html{height:100%;overflow:hidden;}"
                "body{background:var(--bg,#0b1222) fixed;border-radius:0 0 12px 12px;height:100vh;min-height:0;"
                "overflow-y:auto;box-sizing:border-box;}")
            manager = self.web.get_user_content_manager()
            manager.add_style_sheet(WebKit2.UserStyleSheet(
                page_css, WebKit2.UserContentInjectedFrames.TOP_FRAME, WebKit2.UserStyleLevel.USER, None, None))
            self.window.connect("window-state-event", self.on_window_state)

    def on_script_dialog(self, web, dialog):
        """The page's own questions, in a dialog that matches the app (WebKit's has a 'JavaScript - <address>' title)."""
        kind = dialog.get_dialog_type()
        if kind not in (WebKit2.ScriptDialogType.ALERT, WebKit2.ScriptDialogType.CONFIRM):
            return False
        confirm = kind == WebKit2.ScriptDialogType.CONFIRM
        win = Gtk.Window(type=Gtk.WindowType.TOPLEVEL, title=NAME, modal=True, transient_for=self.window,
                         resizable=False, destroy_with_parent=True)
        win.set_type_hint(Gdk.WindowTypeHint.DIALOG)
        win.set_position(Gtk.WindowPosition.CENTER_ON_PARENT)
        win.get_style_context().add_class("zx-dialog")
        visual = win.get_screen().get_rgba_visual()
        if visual is not None and win.get_screen().is_composited():
            win.set_visual(visual)   # see-through only outside the round corners; GTK still paints the gray (not app-paintable)
        bar = Gtk.HeaderBar(title=NAME, show_close_button=False)
        win.set_titlebar(bar)
        body = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=18)
        body.get_style_context().add_class("zx-body")
        text = Gtk.Label(label=dialog.get_message(), wrap=True, max_width_chars=48, xalign=0)
        body.pack_start(text, True, True, 0)
        buttons = Gtk.Box(spacing=10, halign=Gtk.Align.CENTER)
        answer = {"ok": False}
        loop = GLib.MainLoop()

        def done(ok):
            answer["ok"] = ok
            win.destroy()
        if confirm:
            cancel = Gtk.Button(label="Cancel")
            cancel.connect("clicked", lambda *_: done(False))
            buttons.pack_start(cancel, False, False, 0)
        ok = Gtk.Button(label="OK")
        ok.get_style_context().add_class("suggested-action")
        ok.connect("clicked", lambda *_: done(True))
        buttons.pack_start(ok, False, False, 0)
        body.pack_start(buttons, False, False, 0)
        win.add(body)
        win.connect("destroy", lambda *_: loop.quit())
        win.connect("key-press-event", lambda w, e: done(False) if e.keyval == Gdk.KEY_Escape else False)
        win.show_all()
        ok.grab_focus()
        loop.run()   # WebKit waits for the answer
        if confirm:
            dialog.confirm_set_confirmed(answer["ok"])
        return True

    def on_window_state(self, window, event):
        # Maximised or tiled: square corners, as GTK draws them then.
        square = bool(event.new_window_state & (Gdk.WindowState.MAXIMIZED | Gdk.WindowState.TILED | Gdk.WindowState.FULLSCREEN))
        script = "document.body&&(document.body.style.borderRadius='%s')" % ("0" if square else "")
        self.web.evaluate_javascript(script, -1, None, None, None, None, None)
        return False

    def build_tray(self):
        if AppIndicator is None:
            return
        menu = Gtk.Menu()
        self.state_item = Gtk.MenuItem(label="Starting")
        self.state_item.set_sensitive(False)
        menu.append(self.state_item)
        menu.append(Gtk.SeparatorMenuItem())
        item = Gtk.MenuItem(label="Open " + NAME)
        item.connect("activate", lambda *_: self.show_window())
        menu.append(item)
        menu.append(Gtk.SeparatorMenuItem())
        self.disconnect_item = Gtk.MenuItem(label="Disconnect…")
        self.disconnect_item.connect("activate", lambda *_: self.press("forget"))
        menu.append(self.disconnect_item)
        item = Gtk.MenuItem(label="Stop and Quit…")
        item.connect("activate", lambda *_: self.press("stop"))
        menu.append(item)
        menu.append(Gtk.SeparatorMenuItem())
        item = Gtk.MenuItem(label="Remove This Icon (keeps running)")
        item.connect("activate", lambda *_: self.quit_app())
        menu.append(item)
        menu.show_all()
        self.disconnect_item.hide()
        self.indicator = AppIndicator.Indicator.new("zikporx-llm-gateway", ICON,
                                                    AppIndicator.IndicatorCategory.APPLICATION_STATUS)
        self.indicator.set_title(NAME)
        self.indicator.set_status(AppIndicator.IndicatorStatus.ACTIVE)
        self.indicator.set_menu(menu)
        self.indicator.set_secondary_activate_target(menu.get_children()[2])   # middle click opens the window

    # ---- window ----

    def show_window(self):
        self.window.show_all()
        self.window.present()
        if not self.page_shown and (self.launcher is None or self.launcher.poll() is not None) \
                and not os.path.exists(SYSTEM_SERVICE):
            self.start()

    def on_close(self, *_):
        if self.indicator is None:
            self.quit_app()          # no tray on this desktop: closing the window ends the app (the gateway keeps running)
            return False
        self.window.hide()           # the tray icon stays; the gateway keeps running in the background
        return True

    def quit_app(self):
        self.quitting = True
        if self.launcher is not None and self.launcher.poll() is None:
            self.launcher.terminate()
        if self.indicator is not None:
            self.indicator.set_status(AppIndicator.IndicatorStatus.PASSIVE)
        self.release()
        self.quit()

    def keep_icon_at_login(self, on):
        """The gateway itself restarts at login (systemd --user); this brings the tray icon back with it."""
        try:
            if not on:
                os.remove(AUTOSTART)
                return
            os.makedirs(os.path.dirname(AUTOSTART), exist_ok=True)
            entry = ("[Desktop Entry]\nType=Application\nName=" + NAME + "\n"
                     "Exec=/usr/bin/zikporx-llm-gateway --background\nIcon=zikporx-llm-gateway\n"
                     "X-GNOME-Autostart-enabled=true\nNoDisplay=true\n")
            try:
                with open(AUTOSTART) as f:
                    if f.read() == entry:
                        return
            except OSError:
                pass
            with open(AUTOSTART, "w") as f:
                f.write(entry)
        except OSError:
            pass

    # ---- the launcher and the page ----

    def start(self):
        self.page_shown = False
        self.page_url = None
        self.output = []
        self.show_message("Starting " + NAME, "This takes a few seconds.", False)
        env = dict(os.environ, ZIKPORX_HOME=HOME)
        try:
            os.makedirs(HOME, exist_ok=True)
            self.launcher = subprocess.Popen([NODE, MAIN, "open", "--print"], env=env, cwd=HOME,
                                             stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
        except OSError as err:
            self.show_message(NAME + " could not start", str(err), True)
            return
        threading.Thread(target=self.read_launcher, args=(self.launcher,), daemon=True).start()

    def read_launcher(self, process):
        for line in process.stdout:
            GLib.idle_add(self.received, line.rstrip("\n"))
        process.wait()
        GLib.idle_add(self.launcher_exited, process)

    def received(self, line):
        self.output.append(line)
        candidate = line.strip()
        if not self.page_shown and (candidate.startswith("http://localhost:") or candidate.startswith("https://localhost:")):
            self.page_shown = True
            self.page_url = candidate
            self.web.load_uri(candidate)
        return False

    def launcher_exited(self, process):
        if process is self.launcher and not self.page_shown and not self.quitting:
            lines = [l for l in self.output if l.strip()]
            self.show_message(NAME + " could not start", lines[-1] if lines else "The launcher exited without saying why.", True)
        return False

    def show_message(self, title, detail, can_retry):
        self.set_state("Not running" if can_retry else "Starting")
        retry = '<p><a class="button" href="zikporx://retry">Try again</a></p>' if can_retry else ""
        html = ('<!doctype html><html><head><meta charset="utf-8"><style>'
                "body{margin:0;height:100vh;display:flex;align-items:center;justify-content:center;text-align:center;"
                "background:#0b1222;color:#e8ecf6;font:14px/1.5 Ubuntu,'Noto Sans',sans-serif}"
                "div{max-width:420px;padding:24px}h1{font-size:18px;margin:0 0 6px}p{color:#94a3b8;margin:0 0 16px;overflow-wrap:anywhere}"
                ".button{display:inline-block;background:#3b82f6;color:#fff;text-decoration:none;font-weight:600;padding:7px 16px;border-radius:10px}"
                "</style></head><body><div><h1>" + html_escape(title) + "</h1><p>" + html_escape(detail) + "</p>"
                + retry + "</div></body></html>")
        self.web.load_html(html, "about:blank")

    def on_decide_policy(self, web, decision, kind):
        if kind == WebKit2.PolicyDecisionType.NEW_WINDOW_ACTION:
            uri = decision.get_navigation_action().get_request().get_uri()
            decision.ignore()
            if uri.startswith(("http://", "https://", "mailto:")):
                open_link(uri)
            return True
        if kind != WebKit2.PolicyDecisionType.NAVIGATION_ACTION:
            return False
        uri = decision.get_navigation_action().get_request().get_uri()
        if uri.startswith("zikporx://"):
            decision.ignore()
            if uri.startswith("zikporx://quit"):
                # The background service was stopped from the page: nothing should bring the icon back at login.
                self.keep_icon_at_login(False)
                GLib.idle_add(self.quit_app)
            else:
                GLib.idle_add(self.start)   # retry, or the role switch restarting the launcher
            return True
        host = GLib.Uri.parse(uri, GLib.UriFlags.NONE).get_host() if "://" in uri else ""
        if uri.startswith(("about:", "data:")) or (uri.startswith(("http://", "https://")) and host in ("localhost", "127.0.0.1")):
            return False   # only pages served on this computer are shown in the window
        decision.ignore()
        if uri.startswith(("http://", "https://", "mailto:")):
            open_link(uri)
        return True

    # Right click: only the editing items (Cut, Copy, Paste, Select All, spelling), never Reload, Back or Inspect.
    EDIT_ACTIONS = {
        WebKit2.ContextMenuAction.COPY, WebKit2.ContextMenuAction.CUT, WebKit2.ContextMenuAction.PASTE,
        WebKit2.ContextMenuAction.DELETE, WebKit2.ContextMenuAction.SELECT_ALL,
        WebKit2.ContextMenuAction.COPY_LINK_TO_CLIPBOARD,
        WebKit2.ContextMenuAction.SPELLING_GUESS, WebKit2.ContextMenuAction.NO_GUESSES_FOUND,
        WebKit2.ContextMenuAction.IGNORE_SPELLING, WebKit2.ContextMenuAction.LEARN_SPELLING,
    }

    def on_context_menu(self, web, menu, *_):
        for item in list(menu.get_items()):
            if item.get_stock_action() not in self.EDIT_ACTIONS:
                menu.remove(item)
        # tidy separators left at the ends or doubled
        items = menu.get_items()
        keep = []
        for item in items:
            sep = item.is_separator()
            if sep and (not keep or keep[-1].is_separator()):
                menu.remove(item)
            else:
                keep.append(item)
        while keep and keep[-1].is_separator():
            menu.remove(keep.pop())
        return menu.get_n_items() == 0   # nothing left: no menu at all

    def on_load_changed(self, web, event):
        if event == WebKit2.LoadEvent.FINISHED and self.page_shown:
            self.try_pending_press()

    def on_web_crashed(self, *_):
        if self.page_shown:
            self.page_shown = False
            self.show_message(NAME + " stopped responding", "The page inside the window closed unexpectedly.", True)

    # ---- tray menu and state ----

    def page_ready(self):
        return self.page_shown and self.web is not None

    def press(self, button_id):
        """Press one of the page's own buttons, so the tray menu and the window always do the same thing."""
        self.pending_press = button_id
        self.show_window()
        self.try_pending_press()

    def run_js(self, script, done):
        def finished(web, result):
            try:
                value = web.evaluate_javascript_finish(result)
                done(value.to_string() if value is not None else None)
            except Exception:
                done(None)
        self.web.evaluate_javascript(script, -1, None, None, None, finished)

    def try_pending_press(self):
        if self.pending_press is None or not self.page_ready():
            return
        button_id = self.pending_press

        def done(found):
            if found == "true" and self.pending_press == button_id:
                self.pending_press = None
        self.run_js("(function(){var b=document.getElementById('" + button_id + "');"
                    "if(!b||b.offsetParent===null)return false;b.click();return true;})()", done)

    def refresh_state(self):
        if self.quitting:
            return False
        if self.page_ready():
            self.try_pending_press()

            def done(text):
                parts = (text or "").split("|")
                if len(parts) == 2:
                    self.set_state(parts[0] or NAME)
                    if self.disconnect_item is not None:
                        self.disconnect_item.set_visible(parts[1] == "1")
            self.run_js("(function(){function shown(id){var e=document.getElementById(id);return !!e&&e.offsetParent!==null;}"
                        "var p=document.getElementById('state')||document.getElementById('running');"
                        "return (p&&!p.hidden?p.textContent:'')+'|'+(shown('forget')?1:0);})()", done)
            return True
        if self.disconnect_item is not None:
            self.disconnect_item.hide()
        self.health_tick += 1
        if self.health_tick % 4 == 1:
            threading.Thread(target=self.check_health, daemon=True).start()
        return True

    def check_health(self):
        try:
            with open(os.path.join(HOME, "data", "role")) as f:
                role = f.read().strip()
        except OSError:
            role = ""
        port = "8788" if role == "remote" else "8787"
        try:
            with urllib.request.urlopen("http://127.0.0.1:" + port + "/health", timeout=1.5) as r:
                running = r.status == 200
        except Exception:
            running = False
        starting = self.launcher is not None and self.launcher.poll() is None
        GLib.idle_add(lambda: (not self.page_ready()) and self.set_state(
            "Running in the background" if running else ("Starting" if starting else "Not running")) and False)

    def set_state(self, text):
        if self.state_item is not None:
            self.state_item.set_label(text)
        if self.indicator is not None:
            self.indicator.set_title(NAME + ": " + text)
        return False


if __name__ == "__main__":
    # The window class (the dock matches it to the .desktop entry) and where WebKit keeps its data.
    GLib.set_prgname("zikporx-llm-gateway")
    GLib.set_application_name(NAME)
    sys.exit(GatewayApp().run(sys.argv))
