#!/usr/bin/python3
"""mood-open-desktop <desktop-id> [files/uris…] — launch an installed app from its .desktop entry.

Uses GIO (same code path as GNOME), so Exec field codes, Flatpak wrappers, Terminal=true,
DBusActivatable and startup notification all work without gtk-launch (libgtk-3-bin)."""
import os
import sys

import gi

gi.require_version("Gio", "2.0")
from gi.repository import Gio, GLib  # noqa: E402

if len(sys.argv) < 2:
    sys.exit("usage: mood-open-desktop <desktop-id> [uris…]")
did = sys.argv[1]
if not did.endswith(".desktop"):
    did += ".desktop"
info = Gio.DesktopAppInfo.new(did) if "/" not in did else Gio.DesktopAppInfo.new_from_filename(did)
if info is None:
    sys.exit(f"mood-open-desktop: no app {did}")
uris = []
for a in sys.argv[2:]:
    uris.append(a if GLib.uri_peek_scheme(a) else Gio.File.new_for_commandline_arg(a).get_uri())
ctx = Gio.AppLaunchContext()
for k in ("DESKTOP_STARTUP_ID", "XDG_ACTIVATION_TOKEN"):
    ctx.unsetenv(k)
try:
    if info.get_boolean("Terminal"):
        cmd = info.get_commandline() or info.get_executable()
        cmd = " ".join(p for p in GLib.shell_parse_argv(cmd)[1] if not (len(p) == 2 and p[0] == "%"))
        os.execvp("kitty", ["kitty", "sh", "-c", cmd])
    info.launch_uris(uris, ctx)
except GLib.Error as e:
    sys.exit(f"mood-open-desktop: {e.message}")
