#!/usr/bin/env python3
# FWS — « Signaler un problème » : envoi OPTIONNEL et validé par l'utilisateur
# de logs aux développeurs. Rien n'est collecté ni envoyé sans action
# explicite : l'utilisateur remplit le formulaire, voit le payload JSON EXACT
# qui partira (infos système + extrait du journal inclus si la case est
# cochée), puis confirme l'envoi. Aucun daemon, aucune collecte en
# arrière-plan, aucun envoi automatique.
#
# L'envoi passe par curl vers l'API bugs du projet — tout part par CE curl,
# rien d'autre ne quitte la machine :
#   curl -X POST https://fws.laxacube.ch/api/bugs.php
#        -H "Content-Type: application/json"
#        -d '{"app":"FWS","version":"0.7.0","type":"bug","title":"…","description":"…"}'
#
# Usages :
#   fws-bugreport                  → fenêtre GTK (menu « Signaler un problème »)
#   fws-bugreport --file <chemin>  → pré-remplit la description avec un fichier
#                                    de logs existant (écran de debug du live)
#   fws-bugreport --tui            → assistant console (repli sans X / SSH)
#
# Vérifier qu'un envoi est bien parti : la réponse du serveur (code HTTP +
# message, ex. « HTTP 201 — Signalement enregistré. Merci ! (id 13) ») est
# affichée et tracée dans /tmp/fws-bugreport.log.
#
# GTK3 : présent sur tous les bureaux FWS et sur le live (via Anaconda) ;
# sans GTK joignable, l'assistant console prend le relais automatiquement.

import json
import os
import re
import subprocess
import sys
import time
import traceback

# Trace locale de chaque tentative d'envoi (date, code HTTP, réponse du
# serveur) — la façon de vérifier qu'un rapport est bien parti :
#   cat /tmp/fws-bugreport.log
_LOG_PATH = "/tmp/fws-bugreport.log"

_URL = "https://fws.laxacube.ch/api/bugs.php"
_APP = "FWS"

# (valeur envoyée au serveur, libellé affiché)
_TYPES = [
    ("bug", "Bug / panne"),
    ("question", "Question"),
    ("suggestion", "Suggestion"),
    ("other", "Autre"),
]

try:
    import gi

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

    _HAS_GTK = True
except Exception:  # noqa: BLE001 — pas de GTK (système CLI, live minimal…)
    _HAS_GTK = False


# ── Informations système (mêmes sources que fws-about) ───────────────────────

def _osrelease():
    data = {}
    for path in ("/etc/os-release", "/usr/lib/os-release",
                 "/usr/local/share/fws/os-release"):
        try:
            with open(path) as fh:
                for line in fh:
                    m = re.match(r'^([A-Z_]+)=(.*)$', line.strip())
                    if m:
                        data[m.group(1)] = m.group(2).strip('"')
            if data:
                break
        except OSError:
            continue
    return data


def _cmd(*argv):
    try:
        return subprocess.check_output(
            argv, text=True, errors="replace",
            stderr=subprocess.DEVNULL, timeout=10).strip()
    except (OSError, subprocess.CalledProcessError, subprocess.TimeoutExpired):
        return ""


def _cpu():
    try:
        with open("/proc/cpuinfo") as fh:
            for line in fh:
                if line.startswith("model name"):
                    return line.split(":", 1)[1].strip()
    except OSError:
        pass
    return "inconnu"


def _mem():
    try:
        with open("/proc/meminfo") as fh:
            for line in fh:
                if line.startswith("MemTotal"):
                    return f"{int(line.split()[1]) / 1048576:.1f} Gio"
    except OSError:
        pass
    return "inconnue"


def _gpus():
    out = []
    for line in _cmd("lspci").splitlines():
        low = line.lower()
        if "vga" in low or "3d" in low or "display" in low:
            out.append(line.split(":", 2)[-1].strip())
    return out or ["inconnu"]


def _disks():
    out = []
    for line in _cmd("lsblk", "-dno", "NAME,SIZE,MODEL,TYPE").splitlines():
        f = line.split()
        if f and f[-1] == "disk":
            out.append(" ".join(f[:-1]))
    return out or ["inconnu"]


def _desktop():
    if os.environ.get("HYPRLAND_INSTANCE_SIGNATURE"):
        return "Hyprland"
    return (os.environ.get("XDG_CURRENT_DESKTOP")
            or os.environ.get("DESKTOP_SESSION") or "inconnu")


def _session_type():
    t = os.environ.get("XDG_SESSION_TYPE", "")
    return {"wayland": "Wayland", "x11": "X11"}.get(t, t or "inconnu")


def _tail(path, max_lines):
    try:
        with open(path, errors="replace") as fh:
            lines = fh.readlines()
        if len(lines) > max_lines:
            lines = lines[-max_lines:]
        return "".join(lines).rstrip()
    except OSError:
        return ""


def _system_summary(osr):
    rows = [
        ("Système", osr.get("PRETTY_NAME") or "FWS Linux"),
        ("Version", osr.get("VERSION_ID") or "inconnue"),
        ("Build", osr.get("BUILD_ID", "rolling")),
        ("Noyau", _cmd("uname", "-r") or "inconnu"),
        ("Bureau", _desktop()),
        ("Affichage", _session_type()),
        ("Processeur", _cpu()),
        ("Mémoire", _mem()),
        ("Carte(s) graphique(s)", " ; ".join(_gpus())),
        ("Disque(s)", " ; ".join(_disks())),
    ]
    return "\n".join(f"{k}: {v}" for k, v in rows)


def _journal_excerpt(max_lines=200):
    """Extrait du journal (avertissements/erreurs) du dernier démarrage.

    Retourne (accessible, texte) : accessible=False si le journal n'a pas pu
    être lu ; sinon le texte filtré, éventuellement vide si le démarrage ne
    contenait aucun warning/erreur utile.
    """
    try:
        out = subprocess.check_output(
            ["journalctl", "-b", "-p", "warning", "--no-pager"],
            text=True, errors="replace",
            stderr=subprocess.DEVNULL, timeout=20).strip()
    except (OSError, subprocess.CalledProcessError, subprocess.TimeoutExpired):
        return False, ""
    lines = out.splitlines()
    # BRUIT DE L'INSTALLATEUR (vu en réel sur bare metal, 2 ISO successives) :
    # les modules D-Bus d'Anaconda journalisent leur debug SANS marqueur de
    # priorité exploitable — dumps parted (PedPartition 0x…), rapports JSON LVM,
    # listing des 42 tâches, sortie mkfs (« Superblock backups stored on… ») —
    # en INFO/DEBUG journald, donc journalctl -p warning les renvoie quand même,
    # et un filtre à marqueur INFO:/DEBUG: les laisse passer. Un filtre général
    # risquerait d'écraser de VRAIS problèmes d'autres services → on cible :
    # pour les unités org.fedoraproject.Anaconda.* on garde UNIQUEMENT les
    # messages marqués ERROR:/WARNING: — plus les lignes non marquées d'un
    # traceback Python toujours signifiantes (« Traceback (most recent call
    # last): », cadres « File "…", line … » et exception finale, ex.
    # « FileNotFoundError: [Errno 2] … ») — tout le reste du journal passe
    # sans toucher.
    def _jbody(line):
        m = re.search(r"\[\d+\]: ", line)
        return line[m.end():] if m else line

    kept = []
    for ln in lines:
        if "org.fedoraproject.Anaconda." not in ln:
            kept.append(ln)
            continue
        body = _jbody(ln).lstrip()
        if (re.search(r"\b(?:ERROR|WARNING):", ln)
                or body.startswith("Traceback (most recent call last):")
                or body.startswith('File "')
                or re.match(r"^\w[\w.]*(?:Error|Exception)\b", body)):
            kept.append(ln)
    lines = kept

    # « WARNING:py.warnings:… DeprecationWarning: … » : bruit de développement
    # de l'installateur (la même ligne est répétée par chacun des ~12 modules
    # D-Bus d'Anaconda), pas un problème machine — retiré, sauf côté noyau où
    # un warning resterait significatif.
    lines = [ln for ln in lines
             if "DeprecationWarning:" not in ln or re.search(r" kernel: ", ln)]

    # « kernel: ntfs3… » : flot massif émis par le pilote ntfs3 quand
    # l'installateur SONDE la partition Windows (« Correct links count -> N »
    # pour des centaines d'inodes, « N callbacks suppressed »). C'est la
    # correction de liens du système de fichiers Windows pendant la détection
    # des disques — pas un problème FWS, inexploitable dans un rapport (vu en
    # réel sur bare metal : des dizaines de lignes). Retiré ; un vrai problème
    # de disque reste signalé ailleurs (kernel: ata/ahci/nvme…).
    lines = [ln for ln in lines if " kernel: ntfs3" not in ln]

    # Reliques du build (checkout Windows → fichiers PLATS à la place des
    # symlinks systemd, corrigées à la source dans build.sh mais présentes
    # dans les anciennes ISO) : « Failed to preset all unit … already
    # exists » et « … is not a symlink, ignoring » — bruit sans valeur de
    # diagnostic.
    lines = [ln for ln in lines
             if ("Failed to preset all unit" not in ln
                 and "is not a symlink, ignoring" not in ln
                 and "Wants dependency dropin" not in ln)]

    # « anaconda: kickstart: Command X will be parsed in DBus module. » :
    # trace de debug du parseur de kickstart, sans information.
    lines = [ln for ln in lines
             if "will be parsed in DBus module" not in ln]

    # 1) DÉDUPLICATION GLOBALE (vu en réel sur bare metal) : un service en
    # échec boucle (xdg-desktop-portal-gtk sans session graphique) et les
    # modules D-Bus répètent les mêmes warnings — le rapport se noie sous les
    # doublons. Clé = ligne sans horodatage NI chiffres (« 125 »/« 11 » et
    # [pids] s'effacent) : les répétitions à variable numérique près se
    # fusionnent (ex. « fan_curve… (0x110024/25/32) failed » → 1 ligne [×3]),
    # la 1re occurrence garde sa place, marquée « [×N] » — rien n'est perdu,
    # le compte reste lisible.
    _stamp_re = re.compile(r"^[A-Z][a-z]{2} +\d+ +\d\d:\d\d:\d\d +")

    seen = {}
    order = []
    out = []
    for ln in lines:
        m = _stamp_re.match(ln)
        key = re.sub(r"\d+", "#", (ln[m.end():] if m else ln).strip())
        if key in seen:
            seen[key] += 1
            continue
        seen[key] = 1
        order.append(key)
        out.append(ln)
    lines = [ln + (f"  [×{seen[k]}]" if seen[k] > 1 else "")
             for ln, k in zip(out, order)]

    # 2) PLAFOND PAR SOURCE : même uniques, les lignes d'une source en tempête
    # restent des dizaines (xdg-desktop-portal essaie chaque interface du
    # portail l'une après l'autre) — au-delà de 8 lignes de la même source, la
    # suite est omise avec une note explicite. Le noyau n'est pas concerné
    # (pas de [pid] journald dans ses lignes). L'identifiant journald peut
    # être un chemin (« /usr/lib/xdg-desktop-portal[856] ») → l'hostname et
    # l'ident sont séparés par une espace, d'où « \S+ +(.+?)\[pid\] ».
    def _src(line):
        m = re.match(r"^[A-Z][a-z]{2} +\d+ +\d\d:\d\d:\d\d +\S+ +(.+?)\[\d+\]: ", line)
        return m.group(1) if m else None

    capped, counts, omitted = [], {}, {}

    def _note(src, n):
        return (f"    (… +{n} autres lignes de « {src} » omises — "
                "spam répétitif ; journal complet : journalctl -b -p warning)")

    for ln in lines:
        src = _src(ln)
        if src is not None and counts.get(src, 0) >= 8:
            omitted[src] = omitted.get(src, 0) + 1
            continue
        if src is not None:
            counts[src] = counts.get(src, 0) + 1
            if omitted.get(src):
                capped.append(_note(src, omitted[src]))
                omitted[src] = 0
        capped.append(ln)
    for src, n in omitted.items():
        if n:
            capped.append(_note(src, n))
    lines = capped
    if len(lines) > max_lines:
        lines = lines[-max_lines:]
    return True, "\n".join(lines)


def _anaconda_traceback():
    """Le fichier /tmp/anaconda-tb-* le plus récent, s'il existe.

    Quand l'installateur plante, la boîte de dialogue n'affiche que les cadres
    d'appel de l'enveloppe dasbus : la véritable exception n'est QUE dans ce
    fichier. Sans lui, un plantage d'installation est indiagnosticable à
    distance — et comme le live tourne en tmpfs, tout disparaît au redémarrage.
    """
    try:
        names = [os.path.join("/tmp", f) for f in os.listdir("/tmp")
                 if f.startswith("anaconda-tb-")]
    except OSError:
        return ""
    newest, newest_mtime = "", -1.0
    for name in names:
        try:
            if not os.path.isfile(name):
                continue
            mtime = os.path.getmtime(name)
        except OSError:
            continue
        if mtime > newest_mtime:
            newest, newest_mtime = name, mtime
    return newest


def _collect_diagnostics(osr):
    parts = ["===== Informations système =====", _system_summary(osr)]
    # Deux emplacements, et il FAUT les deux : sur le système installé le log
    # est dans /var/log, mais pendant l'installation c'est le %post --nochroot
    # qui le recopie dans le /tmp du live (le disque cible est démonté au moment
    # où on en a besoin). N'en chercher qu'un revenait à envoyer, depuis le live,
    # un rapport SANS le log qui dit si le disque va booter.
    for post_log in ("/var/log/fws-post.log", "/tmp/fws-post-chroot.log"):
        if not os.path.isfile(post_log):
            continue
        tail = _tail(post_log, 100)
        if tail:
            parts += ["", "===== Log d'installation FWS (%s, fin) =====" % post_log,
                      tail]
        break

    tb_path = _anaconda_traceback()
    if tb_path:
        tb = _tail(tb_path, 80)
        if tb:
            parts += ["", "===== Plantage de l'installateur (%s, fin) ====="
                          % tb_path, tb]
    journal_ok, journal = _journal_excerpt()
    if journal:
        parts += ["", "===== Journal du dernier démarrage "
                      "(avertissements / erreurs) =====", journal]
    elif journal_ok:
        # Journal lisible mais rien d'utile après filtrage du bruit : mieux
        # vaut le dire que d'insinuer que le journal était inaccessible.
        parts += ["", "===== Journal du dernier démarrage "
                      "(avertissements / erreurs) =====",
                  "(aucune entrée warning/erreur utile dans le journal)"]
    else:
        parts += ["", "(journal du dernier démarrage inaccessible — "
                      "lance fws-bugreport depuis un terminal avec sudo "
                      "pour l'inclure)"]
    return "\n".join(parts)


def _build_payload(osr, typ, title, description, include_diag):
    description = description.strip()
    if include_diag:
        diag = _collect_diagnostics(osr)
        description = f"{description}\n\n{diag}" if description else diag
    return {
        "app": _APP,
        "version": osr.get("VERSION_ID") or "unknown",
        "type": typ,
        "title": title,
        "description": description,
    }


# ── Envoi (un seul curl, comme spécifié) ─────────────────────────────────────

def _trace(lines):
    try:
        with open(_LOG_PATH, "a",
                  encoding="utf-8", errors="replace") as fh:
            fh.write("\n".join(lines) + "\n")
    except OSError:
        pass


def _send(payload):
    data = json.dumps(payload, ensure_ascii=False).encode("utf-8", "replace")
    # Le corps passe par stdin (--data-binary @-) : pas de limite de taille
    # d'argument (le journal peut faire des centaines de Ko) et aucun souci
    # de quoting. -w ajoute le code HTTP en dernière ligne de stdout.
    try:
        proc = subprocess.run(
            ["curl", "-sS", "--max-time", "30", "-X", "POST", _URL,
             "-H", "Content-Type: application/json",
             "--data-binary", "@-",
             "-w", "\n%{http_code}"],
            input=data, capture_output=True, timeout=45)
    except OSError as exc:
        _trace([f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] ÉCHEC — "
                f"curl introuvable : {exc}"])
        return False, f"curl introuvable : {exc}"
    except subprocess.TimeoutExpired:
        _trace([f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] ÉCHEC — délai "
                "dépassé (30 s)"])
        return False, "Délai dépassé (30 s) — vérifie ta connexion réseau."

    out = proc.stdout.decode("utf-8", "replace")
    err = proc.stderr.decode("utf-8", "replace")
    parts = out.rsplit("\n", 1)
    body = parts[0] if len(parts) == 2 else out
    code = parts[-1].strip()

    if proc.returncode != 0:
        detail = err.strip() or body.strip()
        _trace([f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] ÉCHEC curl "
                f"(code {proc.returncode}) : {detail[:300]}"])
        return False, detail or f"curl a échoué (code {proc.returncode})."

    # Le serveur répond en JSON : {"ok":true,"id":…,"message":…}. Un code
    # HTTP ≥ 400 ne fait PAS échouer curl — on le détecte ici, sinon l'utilisateur
    # verrait « envoyé ✔ » alors que rien n'a été enregistré.
    ok = code.startswith("2")
    msg = body.strip()
    rid = ""
    try:
        j = json.loads(body)
        if isinstance(j, dict):
            ok = bool(j.get("ok")) and code.startswith("2")
            if j.get("message"):
                msg = str(j["message"])
            if j.get("id"):
                rid = f" (id {j['id']})"
    except ValueError:
        pass

    _trace([f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] {_URL} "
            f"app={payload.get('app')} type={payload.get('type')} "
            f"titre={payload.get('title')!r} payload={len(data)} o "
            f"→ HTTP {code or '?'} ok={ok} {msg[:200]}{rid}"])

    if ok:
        return True, f"HTTP {code or '?'} — {msg}{rid}"
    return False, (f"HTTP {code or '?'} — {msg or 'réponse vide'}. "
                   "Le serveur a refusé le rapport.")


# ── Assistant console (repli sans X) ─────────────────────────────────────────

def _tui(preload_path):
    # Robustesse locale : l'assistant console peut tourner dans une console
    # non-UTF-8 (Windows…). On force UTF-8 avec remplacement plutôt que de
    # crasher sur les caractères accentués/boîtes.
    try:
        sys.stdout.reconfigure(encoding="utf-8", errors="replace")
        sys.stdin.reconfigure(encoding="utf-8", errors="replace")
    except (AttributeError, ValueError, OSError):
        pass

    def ask(prompt, default=""):
        try:
            return input(prompt).strip() or default
        except EOFError:
            return default

    print("FWS — « Signaler un problème » (envoi optionnel de logs)")
    print("Rien ne sera envoyé sans ta confirmation.\n")

    if preload_path:
        try:
            with open(preload_path, errors="replace") as fh:
                description = fh.read().strip()
            print(f"Logs chargés depuis {preload_path} "
                  f"({len(description)} caractères).")
        except OSError as exc:
            print(f"  ⚠ Impossible de lire {preload_path} : {exc}")
            description = ""
    else:
        description = ""

    valid_types = [v for v, _l in _TYPES]
    if not description:
        print("Type (défaut : bug) : " + ", ".join(valid_types))
        typ = ask("> ", "bug")
        if typ not in valid_types:
            typ = "bug"
        title = ask("Titre : ")
        print("Description (ligne vide pour terminer) :")
        lines = []
        while True:
            line = ask("> ")
            if not line:
                break
            lines.append(line)
        description = "\n".join(lines)
    else:
        typ = ask("Type (défaut : bug) : ", "bug")
        if typ not in valid_types:
            typ = "bug"
        title = ask("Titre : ")

    if not title:
        print("  ⚠ Titre obligatoire — envoi annulé.")
        return 1

    osr = _osrelease()
    payload = _build_payload(osr, typ, title, description, include_diag=True)
    print("\n─── Aperçu de ce qui sera envoyé à", _URL, "───")
    print(json.dumps(payload, ensure_ascii=False, indent=2))
    if ask("\nEnvoyer ? [o/N] ", "n").lower() not in ("o", "oui", "y", "yes"):
        print("Envoi annulé.")
        return 0
    ok, msg = _send(payload)
    print(("✔ " if ok else "✖ ") + msg)
    if not ok:
        print(f"Détails : {_LOG_PATH}")
    return 0 if ok else 1


# ── Fenêtre GTK (uniquement si GTK est disponible) ───────────────────────────

if _HAS_GTK:
    def _preview_dialog(parent, payload):
        dlg = Gtk.Dialog(title="Confirmer l'envoi", transient_for=parent,
                         modal=True, destroy_with_parent=True)
        dlg.set_default_size(680, 520)
        dlg.set_position(Gtk.WindowPosition.CENTER)
        dlg.add_buttons("Annuler", Gtk.ResponseType.CANCEL,
                        "Confirmer l'envoi", Gtk.ResponseType.OK)

        box = dlg.get_content_area()
        box.set_spacing(10)
        box.set_border_width(14)

        note = Gtk.Label()
        note.set_markup(
            "<b>Voici EXACTEMENT ce qui sera envoyé</b> à "
            "<span font_family='monospace'>https://fws.laxacube.ch/api/bugs.php</span> :")
        note.set_line_wrap(True)
        note.set_xalign(0)
        box.pack_start(note, False, False, 0)

        scroll = Gtk.ScrolledWindow()
        scroll.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
        view = Gtk.TextView()
        view.set_editable(False)
        view.set_cursor_visible(False)
        view.set_monospace(True)
        view.get_buffer().set_text(
            json.dumps(payload, ensure_ascii=False, indent=2))
        scroll.add(view)
        box.pack_start(scroll, True, True, 0)

        dlg.show_all()
        response = dlg.run()
        dlg.destroy()
        return response == Gtk.ResponseType.OK

    def _message(parent, kind, title, text):
        msg_type = (Gtk.MessageType.ERROR if kind == "error"
                    else Gtk.MessageType.INFO)
        dlg = Gtk.MessageDialog(transient_for=parent, modal=True,
                                message_type=msg_type,
                                buttons=Gtk.ButtonsType.CLOSE,
                                text=title)
        if text:
            dlg.format_secondary_text(text)
        dlg.run()
        dlg.destroy()

    class BugReportWindow(Gtk.Window):
        def __init__(self, preload_path=None):
            super().__init__(title="Signaler un problème — FWS")
            self.set_icon_name("fws-bugreport")
            self.set_default_size(580, -1)
            self.set_position(Gtk.WindowPosition.CENTER)
            self.set_border_width(18)
            # DIALOGUE : les tuileurs (i3/Hyprland) gardent les dialogues en
            # flottant → taille naturelle au lieu d'être étirée.
            self.set_type_hint(Gdk.WindowTypeHint.DIALOG)
            self.set_resizable(False)
            self.connect("destroy", Gtk.main_quit)

            self._osr = _osrelease()

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

            title = Gtk.Label()
            title.set_markup(
                "<span size='x-large' weight='bold'>Signaler un problème</span>")
            box.pack_start(title, False, False, 0)

            subtitle = Gtk.Label(
                label="Un souci avec FWS ? Décris-le ci-dessous. Les informations "
                      "système et les logs de diagnostic peuvent être joints pour "
                      "aider les développeurs. Rien ne part sans ta confirmation.")
            subtitle.set_line_wrap(True)
            subtitle.set_xalign(0)
            box.pack_start(subtitle, False, False, 0)

            grid = Gtk.Grid(column_spacing=10, row_spacing=8)
            grid.set_halign(Gtk.Align.FILL)

            grid.attach(Gtk.Label(label="Type :", xalign=1), 0, 0, 1, 1)
            self._type = Gtk.ComboBoxText()
            for value, label in _TYPES:
                self._type.append(value, label)
            self._type.set_active(0)
            grid.attach(self._type, 1, 0, 1, 1)

            grid.attach(Gtk.Label(label="Titre :", xalign=1), 0, 1, 1, 1)
            self._title = Gtk.Entry()
            self._title.set_placeholder_text("Résumé court du problème")
            grid.attach(self._title, 1, 1, 1, 1)

            box.pack_start(grid, False, False, 0)

            desc_label = Gtk.Label(label="Description :", xalign=0)
            box.pack_start(desc_label, False, False, 0)
            scroll = Gtk.ScrolledWindow()
            scroll.set_min_content_height(130)
            scroll.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
            self._description = Gtk.TextView()
            self._description.set_wrap_mode(Gtk.WrapMode.WORD)
            self._description.set_placeholder_text(
                "Ce qui s'est passé, ce que tu attendais, ce que tu as essayé…")
            scroll.add(self._description)
            box.pack_start(scroll, False, False, 0)

            if preload_path:
                try:
                    with open(preload_path, errors="replace") as fh:
                        content = fh.read()
                    self._description.get_buffer().set_text(content)
                    loaded = Gtk.Label()
                    loaded.set_markup(
                        f"<span size='small' foreground='#89b4fa'>Logs chargés "
                        f"depuis <span font_family='monospace'>{preload_path}"
                        f"</span> — tu peux les compléter ou les retirer.</span>")
                    loaded.set_line_wrap(True)
                    loaded.set_xalign(0)
                    box.pack_start(loaded, False, False, 0)
                except OSError as exc:
                    _message(self, "error", "Fichier illisible",
                             f"{preload_path} : {exc}")

            self._include = Gtk.CheckButton(
                label="Joindre les informations système et les logs de diagnostic")
            self._include.set_active(True)
            self._include.set_tooltip_text(
                "Version FWS, matériel détecté, extrait du journal du dernier "
                "démarrage — à relire dans l'aperçu avant l'envoi")
            box.pack_start(self._include, False, False, 4)

            footer = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8)
            cancel = Gtk.Button(label="Fermer")
            cancel.connect("clicked", lambda _b: self.close())
            send = Gtk.Button(label="Envoyer…")
            send.get_style_context().add_class("suggested-action")
            send.connect("clicked", self._on_send)
            footer.pack_end(send, False, False, 0)
            footer.pack_end(cancel, False, False, 0)
            box.pack_start(footer, False, False, 6)

            self._title.connect("activate", self._on_send)

        def _on_send(self, _widget=None):
            # Un crash ne doit JAMAIS mourir en silence (le lancement depuis
            # l'écran de debug du live redirige stderr vers /dev/null) : on
            # trace et on affiche.
            try:
                self._do_send()
            except Exception as exc:  # noqa: BLE001
                _trace(["=== CRASH fws-bugreport ===",
                        traceback.format_exc()])
                _message(self, "error", "Erreur inattendue",
                         f"{exc}\n\nDétails : {_LOG_PATH}")

        def _do_send(self):
            title = self._title.get_text().strip()
            buf = self._description.get_buffer()
            description = buf.get_text(buf.get_start_iter(),
                                       buf.get_end_iter(), True).strip()
            include = self._include.get_active()
            if not title:
                _message(self, "error", "Titre manquant",
                         "Indique un titre court pour le problème.")
                return
            if not description and not include:
                _message(self, "error", "Rapport vide",
                         "Écris une description ou coche la jointure des "
                         "informations système et des logs.")
                return

            typ = self._type.get_active_id() or "bug"
            payload = _build_payload(self._osr, typ, title, description, include)
            if not _preview_dialog(self, payload):
                return
            ok, msg = _send(payload)
            if ok:
                _message(self, "info", "Rapport envoyé ✔",
                         f"{msg}\n\nMerci ! L'équipe FWS a reçu ton rapport.\n"
                         f"(trace : {_LOG_PATH})")
            else:
                _message(self, "error", "Envoi impossible",
                         f"{msg}\n\nTon rapport n'a pas été envoyé. Vérifie ta "
                         f"connexion et réessaie.\nDétails : {_LOG_PATH}")


def main():
    args = sys.argv[1:]
    preload = None
    if "--file" in args:
        i = args.index("--file")
        if i + 1 < len(args):
            preload = args[i + 1]
    if _HAS_GTK and "--tui" not in args and Gtk.init_check()[0]:
        GLib.set_prgname("fws-bugreport")
        win = BugReportWindow(preload)
        win.show_all()
        Gtk.main()
        return 0
    return _tui(preload)


if __name__ == "__main__":
    raise SystemExit(main())