#!/usr/bin/env python3
# FWS — welcome window on first start. Buttons: system update, « Drivers &
# Hardware » (which also installs codecs, games and VR), Proton-GE, keyboard
# shortcuts. Texts come from system-translations.toml (hello.* keys).
# GTK3 : présent sur TOUS les bureaux FWS (Firefox le tire) ;
# python-gobject est installé avec le bureau par le kickstart.
#
# Lancement : /etc/xdg/autostart (KDE/GNOME/XFCE) et exec des configs
# Hyprland/i3, toujours avec --autostart : on se retire sans bruit si
# l'utilisateur a coché « ne plus afficher » (~/.config/fws/hello-done).

import os
import shutil
import subprocess
import sys

import gi

gi.require_version("Gtk", "3.0")
gi.require_version("Gdk", "3.0")  # sinon gi charge Gdk 4.0 (conflit avec Gtk3)
from gi.repository import Gdk, GLib, Gtk  # noqa: E402

sys.path.insert(0, "/usr/local/lib/fws")
from fws_i18n import catalog  # noqa: E402

t = catalog("system").t

# WM_CLASS déterministe : les règles i3/Hyprland « fenêtre flottante »
# ciblent cette classe.
GLib.set_prgname("fws-hello")

_FLAG = os.path.expanduser("~/.config/fws/hello-done")

# (label key, description key, command, in a terminal). Codecs and VR are
# groups of « Drivers & Hardware »: one place to install them, not two.
_ACTIONS = [
    ("hello.update_label", "hello.update_description", "fws-update", True),
    ("hello.drivers_label", "hello.drivers_description", "fws-drivers", False),
    ("hello.proton_label", "hello.proton_description", "fws-proton-ge", True),
]

_TERMINALS = ["kitty", "konsole", "gnome-terminal", "xfce4-terminal", "xterm"]


def _terminal():
    for term in _TERMINALS:
        if shutil.which(term):
            return term
    return None


def _run(command, in_terminal):
    if in_terminal:
        term = _terminal()
        if term is None:
            return
        if term == "gnome-terminal":
            argv = [term, "--", "sh", "-c", command]
        else:
            argv = [term, "-e", "sh", "-c", command]
    else:
        argv = ["sh", "-c", command]
    subprocess.Popen(argv)  # noqa: S603 — commandes internes FWS


class HelloWindow(Gtk.Window):
    def __init__(self):
        super().__init__(title=t("hello.window_title"))
        self.set_default_size(460, -1)
        self.set_position(Gtk.WindowPosition.CENTER)
        self.set_border_width(18)
        # DIALOGUE : les tuileurs (i3/Hyprland) laissent les dialogues en
        # flottant → la fenêtre garde sa taille naturelle au lieu d'être
        # étirée sur tout l'espace de travail (layout illisible sinon).
        self.set_type_hint(Gdk.WindowTypeHint.DIALOG)
        self.set_resizable(False)

        box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12)
        self.add(box)

        title = Gtk.Label()
        title.set_markup("<span size='x-large' weight='bold'>"
                         f"{GLib.markup_escape_text(t('hello.title'))}</span>")
        box.pack_start(title, False, False, 0)

        subtitle = Gtk.Label(label=t("hello.subtitle"))
        subtitle.set_line_wrap(True)
        subtitle.set_xalign(0)
        box.pack_start(subtitle, False, False, 0)

        actions = list(_ACTIONS)
        # Raccourcis clavier : uniquement sur les sessions qui ont fws-keys
        # (Hyprland/i3) — les autres bureaux ont leurs propres réglages.
        session = os.environ.get("XDG_CURRENT_DESKTOP", "").lower()
        if os.environ.get("HYPRLAND_INSTANCE_SIGNATURE") or "i3" in session:
            actions.append(("hello.keys_label", "hello.keys_description",
                            "fws-keys", False))

        for label, desc, command, in_term in actions:
            button = Gtk.Button()
            inner = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=2)
            lab = Gtk.Label()
            lab.set_markup(f"<b>{GLib.markup_escape_text(t(label))}</b>")
            lab.set_xalign(0)
            sub = Gtk.Label(label=t(desc))
            sub.set_xalign(0)
            sub.get_style_context().add_class("dim-label")
            inner.pack_start(lab, False, False, 0)
            inner.pack_start(sub, False, False, 0)
            button.add(inner)
            button.connect("clicked",
                           lambda _b, c=command, term=in_term: _run(c, term))
            box.pack_start(button, False, False, 0)

        self._again = Gtk.CheckButton(label=t("hello.show_again"))
        self._again.set_active(False)
        box.pack_start(self._again, False, False, 6)

        close = Gtk.Button(label=t("common.close"))
        close.connect("clicked", lambda _b: self.close())
        box.pack_start(close, False, False, 0)

        self.connect("destroy", self._on_destroy)

    def _on_destroy(self, _win):
        if not self._again.get_active():
            os.makedirs(os.path.dirname(_FLAG), exist_ok=True)
            with open(_FLAG, "w") as fh:
                fh.write("ok\n")
        else:
            try:
                os.unlink(_FLAG)
            except OSError:
                pass
        Gtk.main_quit()


def main():
    if "--autostart" in sys.argv and os.path.exists(_FLAG):
        return 0
    # Pas d'affichage joignable (lancement hors session graphique) : on se
    # retire sans traceback plutôt que de crasher.
    if not Gtk.init_check()[0]:
        return 1
    win = HelloWindow()
    win.show_all()
    Gtk.main()
    return 0


if __name__ == "__main__":
    sys.exit(main())
