#!/usr/bin/env python3
# FWS — « Pilotes et matériel » : installation des pilotes et de la stack
# matérielle (son, luminosité, Bluetooth, jeux, impression…).
#
# Ce programme ne décide RIEN : toute la détection et toute l'installation
# vivent dans fws-setup-hardware, qu'il appelle. Il n'y a donc qu'une seule
# logique matérielle à maintenir, partagée avec le %post du kickstart.
#   fws-setup-hardware --plan <bureau>      → la liste des groupes (lue ici)
#   fws-setup-hardware --all <bureau>       → installation simple (TOUT le
#       détecté, codecs/jeux/VR compris : c'est le clic de l'utilisateur qui
#       les autorise, l'installateur se limite à --unattended)
#   fws-setup-hardware --groups a,b <bureau>→ installation avancée
#   fws-setup-hardware --check              → vérification/réparation seule
#
# Texts come from system-translations.toml (drivers.* keys); the group names
# come translated from the engine's plan (hardware.* keys).
#
# GTK3 : présent sur TOUS les bureaux FWS (Firefox le tire) ; python-gobject
# est installé avec le bureau par le kickstart — mêmes prérequis que fws-hello.

import os
import shlex
import shutil
import subprocess
import sys
import threading

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-drivers")

_ENGINE = "fws-setup-hardware"
_ENGINE_PATH = "/usr/local/bin/fws-setup-hardware"
_TERMINALS = ["kitty", "konsole", "gnome-terminal", "xfce4-terminal", "xterm"]

# Marqueur SYSTÈME posé par le moteur quand la mise en route matérielle a réussi
# pendant l'installation. S'il existe, « --autostart » ne montre rien.
_SYSTEM_DONE = "/var/lib/fws/hardware-done"
# Marqueur UTILISATEUR : « ne plus me le proposer », même si le système n'a pas
# été configuré. Le choix appartient à l'utilisateur, on ne le harcèle pas.
_USER_DONE = os.path.expanduser("~/.config/fws/drivers-done")


def _session():
    """Identifiant de bureau attendu par le moteur (cli|kde|gnome|xfce|i3|hyprland).

    Le moteur n'en tire que deux choses : session graphique ou non (donc les
    groupes jeux/VR/codecs et les pilotes 32 bits), et le gestionnaire Bluetooth
    à installer. Si la session est inconnue on répond « xfce » : c'est le profil
    « bureau léger sans outil Bluetooth intégré », le plus proche d'un WM nu.
    """
    if os.environ.get("HYPRLAND_INSTANCE_SIGNATURE"):
        return "hyprland"
    desktop = os.environ.get("XDG_CURRENT_DESKTOP", "").lower()
    for name in ("hyprland", "i3", "kde", "gnome", "xfce"):
        if name in desktop:
            return name
    return "xfce"


def _privileged_argv(args):
    """Commande à lancer, en privilégié, SANS terminal.

    pkexec affiche une simple demande de mot de passe graphique (policy
    org.fws.hardware) et la progression s'affiche dans la fenêtre. C'est le
    remplaçant du terminal : une utilisatrice débutante a décrit l'écran noir
    qui défile comme « flippant », et elle avait raison — rien n'y disait que
    tout se passait bien.

    Repli sur sudo dans un terminal SI pkexec est absent ou qu'aucun agent
    d'authentification ne tourne : mieux vaut une fenêtre austère que pas de
    moyen d'installer ses pilotes.
    """
    if shutil.which("pkexec"):
        return ["pkexec", _ENGINE_PATH] + args, True
    term = _terminal()
    if term is None:
        return ["sh", "-c", "sudo " + " ".join([_ENGINE] + args)], False
    command = ("sudo " + " ".join([_ENGINE] + args) + "; echo; echo "
               + shlex.quote(t("common.press_enter_to_close")) + "; read _")
    if term == "gnome-terminal":
        return [term, "--", "sh", "-c", command], False
    return [term, "-e", "sh", "-c", command], False


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


def _plan(session):
    """Groupes proposés par le moteur : [(id, détecté, libellé, [paquets])]."""
    try:
        out = subprocess.run([_ENGINE, "--plan", session],
                             capture_output=True, text=True, timeout=60)
    except Exception:  # pylint: disable=broad-except
        return []
    groups = []
    for line in (out.stdout or "").splitlines():
        parts = line.split("\t")
        if len(parts) != 4:
            continue
        gid, detected, label, packages = parts
        groups.append((gid, detected == "1", label, packages.split()))
    return groups


def _big_button(label, description):
    button = Gtk.Button()
    inner = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=2)
    inner.set_margin_top(6)
    inner.set_margin_bottom(6)
    title = Gtk.Label()
    title.set_markup(f"<b>{GLib.markup_escape_text(label)}</b>")
    title.set_xalign(0)
    sub = Gtk.Label(label=description)
    sub.set_xalign(0)
    sub.set_line_wrap(True)
    sub.get_style_context().add_class("dim-label")
    inner.pack_start(title, False, False, 0)
    inner.pack_start(sub, False, False, 0)
    button.add(inner)
    return button


class DriversWindow(Gtk.Window):
    def __init__(self, autostart=False):
        super().__init__(title=t("drivers.window_title"))
        self._autostart = autostart
        self.set_default_size(560, -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.
        self.set_type_hint(Gdk.WindowTypeHint.DIALOG)

        self._session = _session()
        self._checks = {}
        self.connect("destroy", self._on_destroy)

        self._stack = Gtk.Stack()
        self._stack.set_transition_type(Gtk.StackTransitionType.SLIDE_LEFT_RIGHT)
        self.add(self._stack)
        self._stack.add_named(self._build_home(), "home")
        self._stack.set_visible_child_name("home")

    # ---------------------------------------------------------------- accueil
    def _build_home(self):
        box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12)

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

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

        simple = _big_button(t("drivers.simple_label"),
                             t("drivers.simple_description"))
        simple.connect("clicked", self._on_simple)
        box.pack_start(simple, False, False, 0)

        advanced = _big_button(t("drivers.advanced_label"),
                               t("drivers.advanced_description"))
        advanced.connect("clicked", self._on_advanced)
        box.pack_start(advanced, False, False, 0)

        box.pack_start(Gtk.Separator(), False, False, 6)

        check = _big_button(t("drivers.check_label"),
                            t("drivers.check_description"))
        check.connect("clicked", self._on_check)
        box.pack_start(check, False, False, 0)

        # Proposé seulement quand la fenêtre s'est ouverte d'elle-même : lancée
        # à la main, elle n'a aucune raison de se faire taire.
        self._again = None
        if self._autostart:
            self._again = Gtk.CheckButton(label=t("drivers.dont_offer_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, 6)
        return box

    # ---------------------------------------------------------------- avancé
    def _build_advanced(self, groups):
        box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12)

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

        hint = Gtk.Label(label=t("drivers.advanced_hint"))
        hint.set_line_wrap(True)
        hint.set_xalign(0)
        hint.get_style_context().add_class("dim-label")
        box.pack_start(hint, False, False, 0)

        scroll = Gtk.ScrolledWindow()
        scroll.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
        scroll.set_min_content_height(320)
        listbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=4)
        scroll.add(listbox)
        box.pack_start(scroll, True, True, 0)

        self._checks = {}
        for gid, detected, label, packages in groups:
            check = Gtk.CheckButton()
            check.set_active(detected)
            inner = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)
            head = Gtk.Label()
            mark = GLib.markup_escape_text(label)
            if not detected:
                mark += f" <i>{GLib.markup_escape_text(t('drivers.not_detected'))}</i>"
            head.set_markup(mark)
            head.set_xalign(0)
            head.set_line_wrap(True)
            sub = Gtk.Label(label=" ".join(packages))
            sub.set_xalign(0)
            sub.set_line_wrap(True)
            sub.set_max_width_chars(58)
            sub.get_style_context().add_class("dim-label")
            inner.pack_start(head, False, False, 0)
            inner.pack_start(sub, False, False, 0)
            check.add(inner)
            listbox.pack_start(check, False, False, 0)
            self._checks[gid] = check

        buttons = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8)
        buttons.set_halign(Gtk.Align.END)
        back = Gtk.Button(label=t("drivers.back_button"))
        back.connect("clicked",
                     lambda _b: self._stack.set_visible_child_name("home"))
        install = Gtk.Button(label=t("drivers.install_selection_button"))
        install.get_style_context().add_class("suggested-action")
        install.connect("clicked", self._on_install_selection)
        buttons.pack_start(back, False, False, 0)
        buttons.pack_start(install, False, False, 0)
        box.pack_start(buttons, False, False, 0)
        return box

    def _on_destroy(self, _window):
        if self._again is not None and self._again.get_active():
            try:
                os.makedirs(os.path.dirname(_USER_DONE), exist_ok=True)
                with open(_USER_DONE, "w", encoding="utf-8") as fh:
                    fh.write("1\n")
            except OSError:
                pass

    # ------------------------------------------------------------ progression
    def _build_progress(self, heading):
        """Page « ça travaille » : rassurante, et les détails sont repliés.

        Tout le pari de cette page : montrer qu'il se passe quelque chose et que
        c'est normal, sans imposer le défilement de pacman. Les détails restent
        accessibles d'un clic pour qui veut regarder — ou pour coller dans un
        rapport de bug.
        """
        box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12)

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

        row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=10)
        self._spinner = Gtk.Spinner()
        self._spinner.start()
        row.pack_start(self._spinner, False, False, 0)
        self._status = Gtk.Label(label=t("drivers.status_preparing"))
        self._status.set_xalign(0)
        self._status.set_line_wrap(True)
        row.pack_start(self._status, True, True, 0)
        box.pack_start(row, False, False, 0)

        self._reassure = Gtk.Label(label=t("drivers.reassurance"))
        self._reassure.set_line_wrap(True)
        self._reassure.set_xalign(0)
        self._reassure.get_style_context().add_class("dim-label")
        box.pack_start(self._reassure, False, False, 0)

        expander = Gtk.Expander(label=t("drivers.show_details"))
        scroll = Gtk.ScrolledWindow()
        scroll.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
        scroll.set_min_content_height(240)
        self._log = Gtk.TextView()
        self._log.set_editable(False)
        self._log.set_monospace(True)
        self._log.set_cursor_visible(False)
        scroll.add(self._log)
        expander.add(scroll)
        box.pack_start(expander, True, True, 0)

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

    def _start(self, args, heading):
        argv, graphical = _privileged_argv(args)

        existing = self._stack.get_child_by_name("progress")
        if existing is not None:
            self._stack.remove(existing)
        page = self._build_progress(heading)
        self._stack.add_named(page, "progress")
        page.show_all()
        self._stack.set_visible_child_name("progress")

        if not graphical:
            # Repli terminal : impossible de suivre la sortie depuis ici.
            subprocess.Popen(argv)  # noqa: S603 — commandes internes FWS
            self._spinner.stop()
            self._status.set_text(t("drivers.status_in_terminal"))
            self._reassure.hide()
            self._close.set_sensitive(True)
            return

        try:
            self._proc = subprocess.Popen(  # noqa: S603 — commandes internes FWS
                argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                text=True, bufsize=1)
        except Exception as err:  # pylint: disable=broad-except
            self._finished(None, str(err))
            return
        threading.Thread(target=self._pump, daemon=True).start()

    def _pump(self):
        """Lit la sortie du moteur hors du thread graphique."""
        for line in self._proc.stdout:
            GLib.idle_add(self._append, line.rstrip("\n"))
        self._proc.wait()
        GLib.idle_add(self._finished, self._proc.returncode, None)

    # Engine steps turned into readable sentences, by the tag of their line
    # ("[FWS-hw:install] …"): the engine's text is translated, possibly into
    # another language than the window's (pkexec runs it with the system's), so
    # only the tag is read. The raw lines stay in the details.
    _STEP_PREFIX = "[FWS-hw:"
    _STEPS = {
        "install": "drivers.status_installing",
        "check": "drivers.status_checking",
    }

    def _append(self, line):
        buf = self._log.get_buffer()
        buf.insert(buf.get_end_iter(), line + "\n")
        self._log.scroll_to_iter(buf.get_end_iter(), 0.0, False, 0.0, 0.0)
        if line.startswith(self._STEP_PREFIX):
            step = line[len(self._STEP_PREFIX):].split("]", 1)[0]
            if step in self._STEPS:
                self._status.set_text(t(self._STEPS[step]))
        return False

    def _finished(self, code, error):
        self._spinner.stop()
        self._reassure.hide()
        self._close.set_sensitive(True)
        if error is not None:
            self._show_result(t("drivers.launch_failed"), error)
            return
        if code == 0:
            self._show_result(t("drivers.done_title"), t("drivers.done_body"))
        elif code == 126:
            # pkexec : authentification refusée ou annulée.
            self._show_result(t("drivers.cancelled_title"), t("drivers.cancelled_body"))
        else:
            self._show_result(t("drivers.failed_title"), t("drivers.failed_body"))

    def _show_result(self, title, body):
        """Status line: `title` in bold, then `body` on the next line."""
        self._status.set_markup(f"<b>{GLib.markup_escape_text(title)}</b>\n"
                                + GLib.markup_escape_text(body))

    # ---------------------------------------------------------------- actions
    def _on_simple(self, _button):
        self._start(["--all", self._session], t("drivers.simple_heading"))

    def _on_check(self, _button):
        self._start(["--check"], t("drivers.check_heading"))

    def _on_advanced(self, _button):
        groups = _plan(self._session)
        if not groups:
            dialog = Gtk.MessageDialog(
                transient_for=self, modal=True,
                message_type=Gtk.MessageType.ERROR, buttons=Gtk.ButtonsType.OK,
                text=t("drivers.plan_failed_title"))
            dialog.format_secondary_text(
                t("drivers.plan_failed_detail", command=f"{_ENGINE} --plan"))
            dialog.run()
            dialog.destroy()
            return
        existing = self._stack.get_child_by_name("advanced")
        if existing is not None:
            self._stack.remove(existing)
        page = self._build_advanced(groups)
        self._stack.add_named(page, "advanced")
        page.show_all()
        self._stack.set_visible_child_name("advanced")

    def _on_install_selection(self, _button):
        chosen = [gid for gid, check in self._checks.items() if check.get_active()]
        if not chosen:
            self._stack.set_visible_child_name("home")
            return
        self._start(["--groups", ",".join(chosen), self._session],
                    t("drivers.selection_heading"))


def main():
    autostart = "--autostart" in sys.argv
    if autostart:
        # Mise en route déjà réussie à l'installation, ou refus explicite de
        # l'utilisateur : on se retire sans rien afficher.
        if os.path.exists(_SYSTEM_DONE) or os.path.exists(_USER_DONE):
            return 0
    if not Gtk.init_check()[0]:
        print(t("drivers.no_display", command=f"sudo {_ENGINE}"), file=sys.stderr)
        return 1
    if shutil.which(_ENGINE) is None:
        print(t("drivers.engine_missing", command=_ENGINE), file=sys.stderr)
        return 1
    window = DriversWindow(autostart=autostart)
    window.connect("destroy", lambda _w: Gtk.main_quit())
    window.show_all()
    Gtk.main()
    return 0


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