#!/usr/bin/python3
"""mood-app <id> — open a Mood app in its own window (single instance per app).
Windows use an RGBA visual so Theme Studio's "glass apps" can make them translucent (Wayfire blurs behind)."""
import json
import os
import sys
from pathlib import Path

sys.path.insert(0, "/usr/lib/mood/runtime")
import moodhost  # noqa: E402
from moodhost import Gio, GLib, Gtk  # noqa: E402

APPS = Path("/usr/lib/mood/apps")


class MoodApp(Gtk.Application):
    def __init__(self, app_id):
        super().__init__(application_id=f"os.mood.app.{app_id.replace('-', '_')}", flags=Gio.ApplicationFlags.FLAGS_NONE)
        self.mid = app_id
        self.win = None

    def do_activate(self):
        if self.win and self.win.get_window():
            self.win.present()
            return
        man = json.loads((APPS / self.mid / "manifest.json").read_text())
        win = Gtk.ApplicationWindow(application=self, title=man.get("name", self.mid))
        win.set_icon_name(f"mood-{self.mid}")
        win.set_wmclass(f"mood-{self.mid}", man.get("name", self.mid))
        w, h = man.get("size", [1180, 760])
        win.set_default_size(w, h)
        vis = win.get_screen().get_rgba_visual()
        if vis:
            win.set_visual(vis)
            win.set_app_paintable(True)
        view = moodhost.make_webview(local=True)
        self.bridge = moodhost.Bridge(view, self.mid, window=win)
        view.load_uri((APPS / self.mid / "index.html").as_uri())
        win.add(view)
        win.connect("destroy", self.on_closed)
        win.show_all()
        self.win = win

    def on_closed(self, *_):
        # Closing the window ends the app. Without this a worker thread (Store fetches) or WebKit teardown
        # could keep the process alive, still owning the single-instance D-Bus name, so the next launch
        # would only "present" a window that no longer exists and the app could never be opened again.
        self.win = None
        self.quit()
        GLib.timeout_add(1500, lambda: os._exit(0))


if __name__ == "__main__":
    if len(sys.argv) < 2 or not (APPS / sys.argv[1] / "manifest.json").exists():
        print("usage: mood-app <app-id>", file=sys.stderr)
        sys.exit(2)
    code = MoodApp(sys.argv[1]).run([sys.argv[0]])
    sys.stdout.flush()
    os._exit(code or 0)  # skip interpreter teardown: it can hang on threads/WebKit and keep the app "open"
