#!/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
#   fws-setup-hardware --groups a,b <bureau>→ installation avancée
#   fws-setup-hardware --check              → vérification/réparation seule
#
# 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 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

# 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 'Appuie sur Entrée pour fermer.'; 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="FWS — Pilotes et matériel")
        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'>Pilotes et matériel</span>")
        title.set_xalign(0)
        box.pack_start(title, False, False, 0)

        subtitle = Gtk.Label(
            label="Tout ce qu'il faut pour que ta machine fonctionne au mieux : "
                  "affichage, son, Bluetooth, luminosité, imprimante, jeux.")
        subtitle.set_line_wrap(True)
        subtitle.set_xalign(0)
        box.pack_start(subtitle, False, False, 0)

        simple = _big_button(
            "Installation simple  (recommandé)",
            "FWS installe ce dont ta machine a besoin, puis s'assure que "
            "l'affichage, le son, le Bluetooth et le réseau fonctionnent. "
            "Tu n'as rien à choisir — compte quelques minutes.")
        simple.connect("clicked", self._on_simple)
        box.pack_start(simple, False, False, 0)

        advanced = _big_button(
            "Installation avancée",
            "Pour décider toi-même de ce qui s'installe. Ce qui a été reconnu "
            "sur ta machine est déjà coché.")
        advanced.connect("clicked", self._on_advanced)
        box.pack_start(advanced, False, False, 0)

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

        check = _big_button(
            "Vérifier et réparer seulement",
            "N'installe rien. Regarde si le son, le Bluetooth, le réseau et "
            "l'imprimante répondent, et les remet en route si besoin.")
        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="Ne plus me le proposer au démarrage")
            self._again.set_active(False)
            box.pack_start(self._again, False, False, 6)

        close = Gtk.Button(label="Fermer")
        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'>Installation avancée</span>")
        title.set_xalign(0)
        box.pack_start(title, False, False, 0)

        hint = Gtk.Label(
            label="Ce qui a été reconnu sur ta machine est coché. "
                  "Décoche ce dont tu ne veux pas.")
        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 += " <i>(non détecté sur cette machine)</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="Précédent")
        back.connect("clicked",
                     lambda _b: self._stack.set_visible_child_name("home"))
        install = Gtk.Button(label="Installer la sélection")
        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="Préparation…")
        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="Tu peux laisser cette fenêtre ouverte, il n'y a rien à faire. "
                  "Évite juste d'éteindre la machine maintenant.")
        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="Afficher les détails")
        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="Fermer")
        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(
                "La suite se passe dans la fenêtre de terminal qui vient de s'ouvrir.")
            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)

    # Traduction des étapes du moteur en phrases lisibles. Les libellés bruts
    # restent dans les détails.
    _STEPS = (
        ("groupe «", "Installation : "),
        ("installation :", "Téléchargement et installation des paquets…"),
        ("vérification des services", "Vérification de ton matériel…"),
        ("synchro pacman", "Mise à jour de la liste des logiciels…"),
    )

    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 not line.startswith("[FWS-hw]"):
            return False
        text = line.split("]", 1)[1].strip()
        for needle, friendly in self._STEPS:
            if needle in text:
                if friendly.endswith(": "):
                    # « groupe « Pilotes graphiques — … » » → « Pilotes graphiques »
                    label = text.split("«", 1)[1].rsplit("»", 1)[0]
                    self._status.set_text(friendly + label.split("—")[0].strip())
                else:
                    self._status.set_text(friendly)
                return False
        return False

    def _finished(self, code, error):
        self._spinner.stop()
        self._reassure.hide()
        self._close.set_sensitive(True)
        if error is not None:
            self._status.set_markup(
                "<b>Impossible de lancer l'installation.</b>\n"
                + GLib.markup_escape_text(error))
            return
        if code == 0:
            self._status.set_markup(
                "<b>C'est prêt.</b>\nSi des pilotes graphiques viennent d'être "
                "installés, redémarre pour qu'ils prennent effet.")
        elif code == 126:
            # pkexec : authentification refusée ou annulée.
            self._status.set_markup(
                "<b>Annulé.</b>\nRien n'a été modifié — le mot de passe "
                "administrateur n'a pas été validé.")
        else:
            self._status.set_markup(
                "<b>Tout n'a pas abouti.</b>\nLe plus souvent c'est la connexion "
                "Internet. Vérifie-la puis réessaie ; les détails ci-dessous "
                "disent ce qui a échoué.")

    # ---------------------------------------------------------------- actions
    def _on_simple(self, _button):
        self._start(["--all", self._session], "Installation du nécessaire")

    def _on_check(self, _button):
        self._start(["--check"], "Vérification du matériel")

    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="Impossible de lister le matériel")
            dialog.format_secondary_text(
                f"« {_ENGINE} --plan » n'a rien renvoyé. "
                "L'installation simple reste utilisable.")
            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],
                    "Installation de ta sélection")


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("Aucun serveur graphique : utilise « sudo fws-setup-hardware » "
              "en console.", file=sys.stderr)
        return 1
    if shutil.which(_ENGINE) is None:
        print(f"{_ENGINE} est absent de cette image.", 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())
