import { existsSync } from "node:fs";
import { hostname } from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { createRequire } from "node:module";
import { getManagerStatus, restartDaemon, startDaemon, stopDaemon } from "./daemon-service.js";
const require = createRequire(import.meta.url);
const SysTray = require("systray2").default;
function resolveTrayIcon() {
    const moduleDir = path.dirname(fileURLToPath(import.meta.url));
    const candidate = path.join(moduleDir, "assets", "tray.png");
    if (existsSync(candidate)) {
        return candidate;
    }
    throw new Error("Kong Link tray icon assets are missing from the install.");
}
async function openBrowser(url) {
    const { spawn } = await import("node:child_process");
    if (process.platform === "win32") {
        spawn("cmd", ["/c", "start", "", url], { detached: true, stdio: "ignore", windowsHide: true }).unref();
        return;
    }
    if (process.platform === "darwin") {
        spawn("open", [url], { detached: true, stdio: "ignore" }).unref();
        return;
    }
    spawn("xdg-open", [url], { detached: true, stdio: "ignore" }).unref();
}
function listenPort(listen) {
    const normalized = listen.replace(/^https?:\/\//, "");
    const lastColon = normalized.lastIndexOf(":");
    if (lastColon === -1) {
        return "6769";
    }
    return normalized.slice(lastColon + 1);
}
async function buildMenu() {
    const status = await getManagerStatus();
    const daemon = status.daemon;
    const running = status.health.ok;
    const local = daemon?.localDaemon ?? "unknown";
    const statusLabel = running
        ? "Kong Link — Running"
        : local === "stopped"
            ? "Kong Link — Stopped"
            : "Kong Link — Degraded";
    const host = hostname();
    const tailscaleIp = status.tailscale.ipv4;
    const listen = daemon?.listen ?? status.configListen ?? "0.0.0.0:6769";
    const port = listenPort(listen);
    return {
        icon: resolveTrayIcon(),
        title: "",
        tooltip: running ? "Kong Link — Running" : "Kong Link — Stopped",
        isTemplateIcon: process.platform === "darwin",
        items: [
            { title: statusLabel, enabled: false, tooltip: "" },
            {
                title: `This device: ${host}${tailscaleIp ? ` (${tailscaleIp})` : ""}`,
                enabled: false,
                tooltip: "",
            },
            { title: `Listen: ${listen}`, enabled: false, tooltip: "" },
            SysTray.separator,
            { title: "Start server", enabled: !running, tooltip: "Start Kong Link daemon" },
            { title: "Stop server", enabled: running, tooltip: "Stop Kong Link daemon" },
            { title: "Restart server", enabled: running, tooltip: "Restart Kong Link daemon" },
            SysTray.separator,
            { title: "Open health page", enabled: running, tooltip: status.health.url },
            {
                title: tailscaleIp ? `Remote URL: ${tailscaleIp}:${port}` : "Tailscale: not available",
                enabled: false,
                tooltip: tailscaleIp ? `http://${tailscaleIp}:${port}` : status.tailscale.error ?? "",
            },
            SysTray.separator,
            { title: "Exit tray", tooltip: "Close tray icon (daemon keeps running)" },
        ],
    };
}
export async function runTrayApp() {
    let systray = null;
    let menuLocked = false;
    async function refreshMenu() {
        if (!systray || menuLocked) {
            return;
        }
        menuLocked = true;
        try {
            await systray.sendAction({ type: "update-menu", menu: await buildMenu() });
        }
        finally {
            menuLocked = false;
        }
    }
    systray = new SysTray({
        menu: await buildMenu(),
        copyDir: true,
        debug: false,
    });
    await systray.ready();
    void systray.onClick(async (action) => {
        const title = action.item.title;
        try {
            if (title === "Start server") {
                await startDaemon();
            }
            else if (title === "Stop server") {
                await stopDaemon();
            }
            else if (title === "Restart server") {
                await restartDaemon();
            }
            else if (title === "Open health page") {
                const status = await getManagerStatus();
                if (status.health.url) {
                    await openBrowser(status.health.url);
                }
            }
            else if (title === "Exit tray") {
                await systray?.kill(true);
                return;
            }
        }
        catch (error) {
            process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
        }
        await refreshMenu();
    });
    const interval = setInterval(() => {
        void refreshMenu();
    }, 5000);
    systray.onExit(() => {
        clearInterval(interval);
    });
    return new Promise(() => {
        // Keep process alive while tray is active.
    });
}
