#!/usr/bin/python3

import base64
from concurrent.futures import ThreadPoolExecutor
from datetime import date, datetime
import json
import math
import os
from pathlib import Path
import subprocess
import tempfile
from threading import Lock
import unicodedata
from uuid import uuid4

import gi

gi.require_version("Gtk", "3.0")
gi.require_version("Gdk", "3.0")
from gi.repository import Gdk, GdkPixbuf, Gio, GLib, Gtk
from remote import Agenda, Connections, dialog_for, entry
from vaults import Registry, RegistryError, same
from transcription import show_transcription


APP_ID = "eu.cythin.envorenn"
SHARE = Path(__file__).resolve().parent
CORE = Path("/usr/lib/envorenn/EnvorennLinuxCore")
SECTIONS = {"all": "Tout", "journal": "Journal", "page": "Pages", "memo": "Souvenirs vocaux", "trash": "Corbeille"}
LABELS = {"journal": "Journal", "page": "Page", "memo": "Mémo vocal"}
MONTHS = ["janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre",
          "novembre", "décembre"]
SHORT_MONTHS = ["janv.", "févr.", "mars", "avr.", "mai", "juin", "juil.", "août", "sept.", "oct.", "nov.", "déc."]
# Les mêmes questions que la carte « Question du jour » des applications Apple.
PROMPTS = [
    "Qu'est-ce qui vous a fait sourire aujourd'hui ?",
    "Qu'est-ce qui vous attend demain et vous réjouit ?",
    "Qu'est-ce qui vous a coûté le plus d'énergie ?",
    "Quel petit bonheur voulez-vous garder ?",
    "Qu'avez-vous appris cette semaine ?",
    "À qui avez-vous pensé aujourd'hui ?",
]


def data_directory(variable, default):
    value = Path(os.environ.get(variable) or Path.home() / default)
    return (value if value.is_absolute() else Path.home() / default) / "envorenn"


def searchable(value):
    return "".join(
        character for character in unicodedata.normalize("NFD", value.casefold())
        if not unicodedata.combining(character)
    )


def request(core, vault, device_id, action, **fields):
    result = subprocess.run(
        [core, vault, device_id], input=json.dumps({"action": action, **fields}),
        capture_output=True, text=True, encoding="utf-8",
    )
    if result.returncode:
        raise RuntimeError(result.stderr.strip() or "Le moteur Envorenn s’est arrêté.")
    return json.loads(result.stdout)


def audio_command(*command):
    result = subprocess.run(command, capture_output=True, text=True, errors="replace", stdin=subprocess.DEVNULL)
    if result.returncode:
        raise RuntimeError(result.stderr.strip() or "Le fichier audio n’a pas pu être traité.")
    return result.stdout


def label(text="", style=None):
    widget = Gtk.Label(label=text, xalign=0)
    if style:
        widget.get_style_context().add_class(style)
    return widget


def rounded_top(pixbuf, radius):
    """Arrondit les coins du haut d'une image : GTK 3 ne découpe pas un enfant
    selon les coins arrondis de sa carte."""
    try:
        import cairo
    except ImportError:
        return pixbuf
    width, height = pixbuf.get_width(), pixbuf.get_height()
    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
    context = cairo.Context(surface)
    context.new_sub_path()
    context.arc(width - radius, radius, radius, -math.pi / 2, 0)
    context.line_to(width, height)
    context.line_to(0, height)
    context.arc(radius, radius, radius, math.pi, 3 * math.pi / 2)
    context.close_path()
    context.clip()
    Gdk.cairo_set_source_pixbuf(context, pixbuf, 0, 0)
    context.paint()
    return Gdk.pixbuf_get_from_surface(surface, 0, 0, width, height)


def scroller(widget):
    container = Gtk.ScrolledWindow()
    container.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
    container.add(widget)
    return container


class Window(Gtk.ApplicationWindow):
    def __init__(self, app):
        super().__init__(application=app, title="Envorenn", default_width=1120, default_height=730)
        self.set_icon_name(APP_ID)
        self.set_size_request(760, 500)
        self.connect("delete-event", self.on_close)
        self.worker = ThreadPoolExecutor(max_workers=1)
        self.state = data_directory("XDG_DATA_HOME", ".local/share")
        self.config = data_directory("XDG_CONFIG_HOME", ".config") / "settings.json"
        self.state.mkdir(parents=True, exist_ok=True)
        self.config.parent.mkdir(parents=True, exist_ok=True)
        self.settings = json.loads(self.config.read_text(encoding="utf-8")) if self.config.is_file() else {}
        self.settings.setdefault("device", uuid4().hex[:8])
        self.write_settings()
        # Le registre des coffres (même format que sur Apple). Au premier
        # lancement, il reprend le coffre utilisé jusque-là, là où il est.
        legacy = Path(self.settings.get("vault", self.state / "Vault"))
        self.registry = Registry(self.state / "vaults.json")
        try:
            self.registry.load_or_create(legacy, "Mon coffre")
            self.vault = self.registry.root(self.registry.active)
        except (RegistryError, OSError, ValueError):
            # Un registre abîmé n'est ni deviné ni écrasé : on ouvre le coffre
            # habituel, sans liste de coffres.
            self.registry = None
            self.vault = legacy
        self.temp = tempfile.TemporaryDirectory(prefix="envorenn-")
        self.recording = None
        self.playback = None
        self.pending = False
        self.items = []
        self.selected = None
        self.connections = Connections(self)
        self.agenda = Agenda(self, self.connections)

        # La fenêtre suit celle du Mac : navigation à gauche, chronologie de
        # cartes à droite, boutons flottants « micro » et « Écrire ».
        self.filter = ("section", "journal")
        self.prompt = date.today().toordinal() % len(PROMPTS)
        self.thumbnails = {}
        self.thumbnail_worker = ThreadPoolExecutor(max_workers=2)
        # Éditeur intégré : une seule écriture à la fois, chacune sur la
        # révision que la précédente vient de publier.
        self.save_worker = ThreadPoolExecutor(max_workers=1)
        self.editing = None
        self.save_timer = None
        self.saves_in_flight = 0
        self.list_dirty = False

        header = Gtk.HeaderBar(title="Journal", subtitle=self.vault_subtitle(), show_close_button=True)
        self.header = header
        self.set_titlebar(header)

        self.actions_menu = Gtk.Menu()
        for title, callback in [
            ("Actualiser", lambda: self.reload(refresh=True)),
            ("Synchroniser", self.connections.sync),
            ("Dossier synchronisé…", self.connections.choose_folder),
            ("Connexion Nextcloud…", lambda: self.connections.configure("nextcloud")),
            ("Importer un fichier audio…", self.import_audio),
            ("Exporter…", self.export),
            ("Ouvrir les fichiers du coffre", lambda: self.open_path(self.vault)),
        ]:
            item = Gtk.MenuItem(label=title)
            item.connect("activate", lambda _, callback=callback: callback() if not self.pending and not self.recording else None)
            self.actions_menu.append(item)
        self.actions_menu.show_all()
        more = Gtk.MenuButton()
        more.set_image(Gtk.Image.new_from_icon_name("view-more-symbolic", Gtk.IconSize.BUTTON))
        more.set_tooltip_text("Coffre et synchronisation")
        more.set_popup(self.actions_menu)
        header.pack_end(more)
        self.search = Gtk.SearchEntry(placeholder_text="Rechercher")
        self.search.set_width_chars(26)
        self.search.connect("search-changed", self.render_timeline)
        header.pack_end(self.search)

        self.body = Gtk.Paned(orientation=Gtk.Orientation.HORIZONTAL)
        self.add(self.body)
        self.body.pack1(self.build_sidebar(), resize=False, shrink=False)
        self.body.set_position(286)

        overlay = Gtk.Overlay()
        self.body.pack2(overlay, resize=True, shrink=False)
        self.stack = Gtk.Stack(transition_type=Gtk.StackTransitionType.SLIDE_LEFT_RIGHT, transition_duration=180)
        overlay.add(self.stack)
        self.timeline = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=14)
        self.timeline.get_style_context().add_class("timeline")
        self.timeline_scroller = scroller(self.timeline)
        self.stack.add_named(self.timeline_scroller, "timeline")
        self.detail = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=14)
        self.detail.get_style_context().add_class("detail")
        self.stack.add_named(scroller(self.detail), "detail")

        floating = Gtk.Box(spacing=14, halign=Gtk.Align.CENTER, valign=Gtk.Align.END)
        floating.set_margin_bottom(22)
        self.record_button = Gtk.Button()
        self.record_button.set_image(Gtk.Image.new_from_icon_name("audio-input-microphone-symbolic", Gtk.IconSize.LARGE_TOOLBAR))
        self.record_button.set_tooltip_text("Enregistrer la voix")
        self.record_button.get_style_context().add_class("fab-record")
        self.record_button.connect("clicked", lambda _: self.record())
        floating.pack_start(self.record_button, False, False, 0)
        write = Gtk.Button()
        content = Gtk.Box(spacing=8)
        content.pack_start(Gtk.Image.new_from_icon_name("document-edit-symbolic", Gtk.IconSize.BUTTON), False, False, 0)
        content.pack_start(Gtk.Label(label="Écrire"), False, False, 0)
        write.add(content)
        write.get_style_context().add_class("fab-write")
        write.connect("clicked", lambda _: self.edit(self.writing_kind()))
        floating.pack_start(write, False, False, 0)
        overlay.add_overlay(floating)
        # Comme sur le Mac, les boutons flottants n'accompagnent que la
        # chronologie : dans l'éditeur, ils couvriraient les tags.
        self.stack.connect("notify::visible-child-name",
                           lambda stack, _: floating.set_visible(stack.get_visible_child_name() == "timeline"))

        group = Gtk.AccelGroup()
        self.add_accel_group(group)
        for key, callback in [
            ("<Primary>n", lambda: self.edit(self.writing_kind())),
            ("<Primary>f", self.search.grab_focus),
            ("<Primary>r", lambda: self.reload(refresh=True)),
            ("Escape", self.show_timeline),
        ]:
            keyval, modifiers = Gtk.accelerator_parse(key)
            group.connect(keyval, modifiers, Gtk.AccelFlags.VISIBLE, lambda *_, callback=callback: (callback(), True)[1])
        self.show_all()
        self.reload(refresh=True)

    # MARK: - Barre latérale

    def build_sidebar(self):
        sidebar = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        sidebar.get_style_context().add_class("sidebar")
        top = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10)
        top.set_border_width(12)
        sidebar.pack_start(top, False, False, 0)

        # Le coffre ouvert et le menu pour en changer, comme sur Apple.
        self.vault_menu = Gtk.Menu()
        self.vault_button = Gtk.MenuButton()
        self.vault_button.get_style_context().add_class("vault-switcher")
        self.vault_button.set_popup(self.vault_menu)
        top.pack_start(self.vault_button, False, False, 0)
        self.rebuild_vault_menu()

        new = Gtk.Button()
        content = Gtk.Box(spacing=8)
        content.pack_start(Gtk.Image.new_from_icon_name("list-add-symbolic", Gtk.IconSize.BUTTON), False, False, 0)
        self.new_label = Gtk.Label(label="Nouvelle entrée")
        content.pack_start(self.new_label, False, False, 0)
        new.add(content)
        new.get_style_context().add_class("new-entry")
        new.connect("clicked", lambda _: self.edit(self.writing_kind()))
        top.pack_start(new, False, False, 0)

        self.navigation = Gtk.ListBox()
        self.navigation.get_style_context().add_class("navigation")
        self.navigation.connect("row-selected", self.navigate)
        sidebar.pack_start(scroller(self.navigation), True, True, 0)

        bottom = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=2)
        bottom.get_style_context().add_class("sidebar-footer")
        for icon, title, callback in [
            ("user-trash-symbolic", "Corbeille", lambda: self.set_filter(("section", "trash"))),
            ("emblem-system-symbolic", "Réglages", lambda: self.actions_menu.popup_at_pointer(None)),
        ]:
            button = Gtk.Button()
            button.add(self.nav_content(icon, title))
            button.set_relief(Gtk.ReliefStyle.NONE)
            button.get_style_context().add_class("sidebar-action")
            button.connect("clicked", lambda _, callback=callback: callback())
            bottom.pack_start(button, False, False, 0)
        self.status = label("", "status")
        self.status.set_line_wrap(True)
        bottom.pack_start(self.status, False, False, 0)
        sidebar.pack_end(bottom, False, False, 0)
        return sidebar

    @staticmethod
    def nav_content(icon, title):
        box = Gtk.Box(spacing=10)
        box.pack_start(Gtk.Image.new_from_icon_name(icon, Gtk.IconSize.MENU), False, False, 0)
        text = Gtk.Label(label=title, xalign=0)
        text.set_ellipsize(3)
        box.pack_start(text, True, True, 0)
        return box

    def rebuild_navigation(self):
        self.navigation.handler_block_by_func(self.navigate)
        try:
            for child in self.navigation.get_children():
                child.destroy()

            def row(key, icon, title):
                item = Gtk.ListBoxRow()
                item.key = key
                item.add(self.nav_content(icon, title))
                self.navigation.add(item)
                if key == self.filter:
                    self.navigation.select_row(item)

            def heading(title):
                item = Gtk.ListBoxRow(selectable=False, activatable=False)
                item.add(label(title, "nav-heading"))
                self.navigation.add(item)

            row(("section", "journal"), "x-office-document-symbolic", "Journal")
            row(("agenda", None), "x-office-calendar-symbolic", "Agenda")
            row(("section", "memo"), "audio-input-microphone-symbolic", "Souvenirs vocaux")
            row(("section", "page"), "text-x-generic-symbolic", "Pages")
            live = [item for item in self.items if not item["deleted"]]
            tags = sorted({tag for item in live for tag in item["tags"]}, key=searchable)
            collections = sorted({name for item in live for name in item["collections"]}, key=searchable)
            if tags:
                heading("Tags")
                for tag in tags:
                    row(("tag", tag), "user-bookmarks-symbolic", tag)
            if collections:
                heading("Collections")
                for name in collections:
                    row(("collection", name), "folder-symbolic", name)
            self.navigation.show_all()
        finally:
            self.navigation.handler_unblock_by_func(self.navigate)

    def navigate(self, _, row):
        if row is None:
            return
        if row.key[0] == "agenda":
            # L'agenda s'ouvre dans sa fenêtre ; la sélection revient au filtre
            # en cours, une fois le signal terminé.
            self.agenda.show()
            GLib.idle_add(lambda: (self.rebuild_navigation(), False)[1])
            return
        self.set_filter(row.key, from_navigation=True)

    def set_filter(self, key, from_navigation=False):
        self.filter = key
        self.search.set_text("")
        if not from_navigation:
            self.rebuild_navigation()
        self.show_timeline()
        self.render_timeline()

    def filter_title(self):
        kind, value = self.filter
        return SECTIONS.get(value, "Journal") if kind == "section" else value

    def writing_kind(self):
        return "page" if self.filter == ("section", "page") else "journal"

    @staticmethod
    def button(pack, title, callback):
        widget = Gtk.Button(label=title)
        widget.connect("clicked", lambda _: callback())
        pack(widget)
        return widget

    def write_settings(self):
        with tempfile.NamedTemporaryFile(dir=self.config.parent, delete=False, mode="w", encoding="utf-8") as handle:
            temporary = Path(handle.name)
            json.dump(self.settings, handle)
        try:
            temporary.replace(self.config)
        finally:
            temporary.unlink(missing_ok=True)

    def command(self, action, **fields):
        return request(CORE, self.vault, self.settings["device"], action, **fields)

    def notify(self, message, kind=Gtk.MessageType.INFO):
        dialog = Gtk.MessageDialog(
            transient_for=self, modal=True, message_type=kind, buttons=Gtk.ButtonsType.OK, text=message,
        )
        dialog.run()
        dialog.destroy()

    def confirm(self, message):
        dialog = Gtk.MessageDialog(
            transient_for=self, modal=True, message_type=Gtk.MessageType.QUESTION,
            buttons=Gtk.ButtonsType.OK_CANCEL, text=message,
        )
        result = dialog.run()
        dialog.destroy()
        return result == Gtk.ResponseType.OK

    def run_job(self, message, job, completed, failed=None):
        if self.pending:
            return
        self.pending = True
        self.status.set_text(message)
        self.body.set_sensitive(False)

        def finish(future):
            self.pending = False
            self.body.set_sensitive(True)
            self.status.set_text("")
            try:
                completed(future.result())
            except Exception as error:
                if failed:
                    failed(error)
                else:
                    self.notify(str(error), Gtk.MessageType.ERROR)
            return False

        self.worker.submit(job).add_done_callback(lambda future: GLib.idle_add(finish, future))

    def reload(self, refresh=False, selected=None):
        self.run_job("Lecture du coffre…", lambda: self.command("refresh" if refresh else "list"),
                     lambda result: self.loaded(result, selected))

    def loaded(self, result, selected):
        self.items = result["items"]
        self.selected = selected or self.selected
        self.thumbnails.clear()
        self.rebuild_navigation()
        self.render_timeline()
        self.status.set_text(result.get("message") or f"{len(self.items)} élément(s) dans le coffre")
        if self.selected and self.stack.get_visible_child_name() == "detail":
            current = next((item for item in self.items if self.row_key(item) == self.selected), None)
            if current:
                self.open_item(current)
            else:
                self.show_timeline()

    @staticmethod
    def row_key(item):
        return item["group"], item["id"], item["deleted"]

    def visible_items(self):
        kind, value = self.filter
        words = searchable(self.search.get_text()).split()
        for item in self.items:
            if item["deleted"] != (self.filter == ("section", "trash")):
                continue
            if kind == "section" and value not in {"all", "trash", item["group"]}:
                continue
            if kind == "tag" and value not in item["tags"]:
                continue
            if kind == "collection" and value not in item["collections"]:
                continue
            haystack = searchable(" ".join([item["title"], item["search"], *item["tags"], *item["collections"]]))
            if all(word in haystack for word in words):
                yield item

    def render_timeline(self, *_):
        for child in self.timeline.get_children():
            child.destroy()
        self.header.set_title(self.filter_title())
        self.new_label.set_text("Nouvelle page" if self.writing_kind() == "page" else "Nouvelle entrée")

        chip = Gtk.Button()
        chip.set_relief(Gtk.ReliefStyle.NONE)
        chip.get_style_context().add_class("sync-chip")
        chip.add(self.nav_content(*self.sync_summary()))
        chip.set_halign(Gtk.Align.START)
        chip.connect("clicked", lambda _: self.actions_menu.popup_at_pointer(None))
        self.timeline.pack_start(chip, False, False, 0)

        searching = bool(self.search.get_text().strip())
        if self.filter == ("section", "journal") and not searching:
            self.timeline.pack_start(self.prompt_card(), False, False, 0)

        items = list(self.visible_items())
        if not items:
            empty = label("Aucun résultat." if searching else "Rien ici pour l’instant. Commencez à écrire.", "empty")
            empty.set_halign(Gtk.Align.CENTER)
            self.timeline.pack_start(empty, False, False, 24)
        month = None
        for item in items:
            moment = self.local_date(item)
            if (moment.year, moment.month) != month:
                month = (moment.year, moment.month)
                self.timeline.pack_start(label(f"{MONTHS[moment.month - 1]} {moment.year}", "month"), False, False, 0)
            self.timeline.pack_start(self.card(item), False, False, 0)
        # Place pour les boutons flottants, sous la dernière carte.
        self.timeline.pack_start(Gtk.Box(height_request=80), False, False, 0)
        self.timeline.show_all()

    def sync_summary(self):
        settings = self.connections.settings()
        if settings.get("folder"):
            return "folder-remote-symbolic", f"Dossier synchronisé · {Path(settings['folder']['path']).name}"
        profile = settings.get("nextcloud")
        if profile:
            host = profile.get("server", "").split("//")[-1].split("/")[0]
            return "network-server-symbolic", f"Nextcloud · {host}"
        return "computer-symbolic", "Sur cet appareil"

    def prompt_card(self):
        box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10)
        box.get_style_context().add_class("card")
        box.get_style_context().add_class("prompt")
        box.pack_start(self.nav_content("starred-symbolic", "Question du jour"), False, False, 0)
        question = label(PROMPTS[self.prompt], "prompt-question")
        question.set_line_wrap(True)
        box.pack_start(question, False, False, 0)
        buttons = Gtk.Box(spacing=10)
        write = Gtk.Button(label="Écrire là-dessus")
        write.get_style_context().add_class("prompt-write")
        write.connect("clicked", lambda _: self.edit("journal", prefill=PROMPTS[self.prompt] + "\n\n"))
        other = Gtk.Button(label="Une autre")
        other.connect("clicked", lambda _: self.next_prompt())
        buttons.pack_start(write, False, False, 0)
        buttons.pack_start(other, False, False, 0)
        box.pack_start(buttons, False, False, 0)
        return box

    def next_prompt(self):
        self.prompt = (self.prompt + 1) % len(PROMPTS)
        self.render_timeline()

    def card(self, item):
        event = Gtk.EventBox()
        event.connect("button-release-event", lambda *_: self.open_item(item))
        box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        box.get_style_context().add_class("card")
        event.add(box)
        if item.get("photo"):
            picture = Gtk.Image()
            picture.get_style_context().add_class("card-photo")
            box.pack_start(picture, False, False, 0)
            self.load_thumbnail(item, picture)
        text = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
        text.get_style_context().add_class("card-body")
        box.pack_start(text, False, False, 0)
        title = label(item["title"], "card-title")
        title.set_line_wrap(True)
        text.pack_start(title, False, False, 0)
        preview = item.get("preview") or ("" if item["group"] != "memo" else item.get("search", ""))
        if preview:
            excerpt = label(preview, "card-preview")
            excerpt.set_line_wrap(True)
            excerpt.set_lines(3)
            excerpt.set_ellipsize(3)
            text.pack_start(excerpt, False, False, 0)
        categories = " · ".join([*item["tags"], *item["collections"]])
        if categories:
            text.pack_start(label(categories, "meta"), False, False, 0)
        text.pack_start(Gtk.Separator(), False, False, 4)
        when = self.local_date(item)
        stamp = f"{when.day} {SHORT_MONTHS[when.month - 1]} {when.year} à {when:%H:%M}"
        if item["conflict"]:
            stamp += " · Version concurrente"
        if item["group"] != "journal":
            stamp = f"{LABELS[item['group']]} · {stamp}"
        text.pack_start(label(stamp, "meta"), False, False, 0)
        return event

    def load_thumbnail(self, item, picture):
        # Largeur de la carte : la chronologie moins ses marges et la bordure.
        width = max(320, self.timeline_scroller.get_allocated_width() - 50)
        key = (item["id"], width)
        if key in self.thumbnails:
            picture.set_from_pixbuf(self.thumbnails[key])
            return
        vault, device = self.vault, self.settings["device"]

        def fetch():
            reply = request(CORE, vault, device, "open", **self.fields(item))
            photos = reply.get("photos") or []
            if not photos:
                return None
            loader = GdkPixbuf.PixbufLoader.new()
            loader.write(base64.b64decode(photos[0]))
            loader.close()
            pixbuf = loader.get_pixbuf()
            # Recadrée au centre, sur la largeur de la carte, comme sur le Mac.
            height = 220
            scale = max(width / pixbuf.get_width(), height / pixbuf.get_height())
            scaled = pixbuf.scale_simple(max(1, round(pixbuf.get_width() * scale)),
                                         max(1, round(pixbuf.get_height() * scale)), GdkPixbuf.InterpType.BILINEAR)
            x = max(0, (scaled.get_width() - width) // 2)
            y = max(0, (scaled.get_height() - height) // 2)
            cropped = scaled.new_subpixbuf(x, y, min(width, scaled.get_width()), min(height, scaled.get_height())).copy()
            return rounded_top(cropped, 16)

        def done(future):
            try:
                pixbuf = future.result()
            except Exception:
                return False
            if pixbuf is not None:
                self.thumbnails[key] = pixbuf
                if picture.get_parent() is not None:
                    picture.set_from_pixbuf(pixbuf)
            return False

        self.thumbnail_worker.submit(fetch).add_done_callback(lambda future: GLib.idle_add(done, future))

    @staticmethod
    def local_date(item):
        return datetime.fromisoformat(item["date"].replace("Z", "+00:00")).astimezone()

    @staticmethod
    def date_label(item):
        when = Window.local_date(item)
        return f"{when.day} {MONTHS[when.month - 1]} {when.year} à {when:%H:%M}"

    @staticmethod
    def fields(item):
        return {"id": item["id"], "kind": item["group"], "trashed": item["deleted"]}

    def show_timeline(self):
        self.flush_save()
        self.editing = None
        self.selected = None
        self.stack.set_visible_child_name("timeline")
        if self.list_dirty and self.saves_in_flight == 0:
            self.list_dirty = False
            self.reload()

    def open_item(self, item):
        self.flush_save()
        self.selected = self.row_key(item)
        editable = item["group"] != "memo" and not item["deleted"] and not item["conflict"]
        self.show_detail()
        self.stack.set_visible_child_name("detail")

        def opened(result):
            if self.selected != self.row_key(item):
                return
            if editable:
                self.show_editor(item["group"], item, result)
            else:
                self.show_detail(result, item)

        self.run_job("Ouverture…", lambda: self.command("open", **self.fields(item)), opened)
        return True

    # MARK: - Éditeur intégré

    def show_editor(self, kind, item=None, result=None, prefill=""):
        """L'écriture se fait dans la page, comme sur le Mac : pas de bouton
        « Enregistrer », chaque pause de la frappe publie une révision."""
        for child in self.detail.get_children():
            child.destroy()
        top = Gtk.Box(spacing=8)
        back = Gtk.Button()
        back.set_relief(Gtk.ReliefStyle.NONE)
        back.get_style_context().add_class("back")
        back.add(self.nav_content("go-previous-symbolic", self.filter_title()))
        back.connect("clicked", lambda _: self.show_timeline())
        top.pack_start(back, False, False, 0)
        status = label("", "save-status")
        top.pack_end(status, False, False, 0)
        self.detail.pack_start(top, False, False, 0)
        when = self.date_label(item) if item else self.date_label({"date": datetime.now().astimezone().isoformat()})
        self.detail.pack_start(label(f"{LABELS[kind]}  ·  {when}", "meta"), False, False, 0)

        actions = Gtk.Box(spacing=6)
        actions.get_style_context().add_class("editor-actions")
        self.detail.pack_start(actions, False, False, 0)

        def action(icon, tooltip, callback):
            button = Gtk.Button()
            button.set_image(Gtk.Image.new_from_icon_name(icon, Gtk.IconSize.BUTTON))
            button.set_tooltip_text(tooltip)
            button.set_relief(Gtk.ReliefStyle.NONE)
            button.connect("clicked", lambda _: callback())
            actions.pack_start(button, False, False, 0)

        photos = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10)
        self.detail.pack_start(photos, False, False, 0)
        for photo in (result or {}).get("photos", []):
            self.add_photo(photos, base64.b64decode(photo))

        text = Gtk.TextView(wrap_mode=Gtk.WrapMode.WORD_CHAR, top_margin=8, bottom_margin=8)
        text.get_style_context().add_class("editor")
        buffer = text.get_buffer()
        title_tag = buffer.create_tag("title", weight=700, scale=1.6, pixels_below_lines=8)
        buffer.set_text((result or {}).get("text") or prefill)

        def style_title(*_):
            start, end = buffer.get_bounds()
            buffer.remove_tag(title_tag, start, end)
            line_end = buffer.get_start_iter()
            line_end.forward_to_line_end()
            buffer.apply_tag(title_tag, buffer.get_start_iter(), line_end)

        style_title()
        self.detail.pack_start(text, True, True, 0)

        organization = Gtk.Box(spacing=10)
        organization.get_style_context().add_class("organization")
        tags = Gtk.Entry(placeholder_text="Tags", text=", ".join((item or {}).get("tags", [])))
        collections = Gtk.Entry(placeholder_text="Collections", text=", ".join((item or {}).get("collections", [])))
        for icon, entry in [("user-bookmarks-symbolic", tags), ("folder-symbolic", collections)]:
            entry.set_icon_from_icon_name(Gtk.EntryIconPosition.PRIMARY, icon)
            organization.pack_start(entry, True, True, 0)
        self.detail.pack_start(organization, False, False, 0)

        session = {
            "kind": kind, "id": item["id"] if item else None, "lock": Lock(), "photo": None,
            "buffer": buffer, "tags": tags, "collections": collections, "status": status,
            "saved": self.editor_snapshot(buffer, tags, collections) if item else None,
        }
        self.editing = session
        for signal_source, signal in [(buffer, "changed"), (tags, "changed"), (collections, "changed")]:
            signal_source.connect(signal, lambda *_: self.schedule_save())
        buffer.connect("changed", style_title)

        def attach_photo():
            path = self.choose("Joindre une photo", Gtk.FileChooserAction.OPEN)
            if not path:
                return
            try:
                pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(path, 1800, 1800, True)
            except GLib.Error as failure:
                status.set_text(f"Photo illisible : {failure.message}")
                return
            target = Path(self.temp.name) / f"{uuid4().hex}.jpg"
            pixbuf.savev(str(target), "jpeg", ["quality"], ["88"])
            session["photo"] = str(target)
            for child in photos.get_children():
                child.destroy()
            self.add_photo(photos, target.read_bytes())
            session["saved"] = None
            self.schedule_save(immediately=True)

        action("insert-image-symbolic", "Joindre ou remplacer la photo", attach_photo)
        if item and result:
            if result.get("audio"):
                action("media-playback-start-symbolic", "Écouter / arrêter", lambda: self.journal_audio(item))
                action("format-justify-left-symbolic",
                       "Revoir la transcription" if result.get("transcript") else "Transcrire l’audio",
                       lambda: show_transcription(self, item, result, SHARE / "ggml-base-q5_1.bin", CORE.with_name("whisper-cli")))
            for attachment in result.get("media", []):
                action("document-save-symbolic", f"Enregistrer {attachment['filename']}",
                       lambda attachment=attachment: self.save_media(item, attachment))
            action("user-trash-symbolic", "Mettre à la corbeille",
                   lambda: self.confirm("Mettre cet élément à la corbeille ?") and self.trash_edited(item))
        self.detail.show_all()
        text.grab_focus()
        if not item:
            text.get_buffer().place_cursor(buffer.get_end_iter())

    def add_photo(self, box, data):
        loader = GdkPixbuf.PixbufLoader.new()
        loader.connect("size-prepared", self.limit_image, 560)
        try:
            loader.write(data)
            loader.close()
            picture = Gtk.Image.new_from_pixbuf(loader.get_pixbuf())
            picture.set_halign(Gtk.Align.START)
            box.pack_start(picture, False, False, 0)
            box.show_all()
        except GLib.Error:
            box.pack_start(label("La photo n’a pas pu être affichée.", "meta"), False, False, 0)

    @staticmethod
    def editor_snapshot(buffer, tags, collections):
        return (buffer.get_text(*buffer.get_bounds(), False), tags.get_text(), collections.get_text())

    def schedule_save(self, immediately=False):
        if self.save_timer:
            GLib.source_remove(self.save_timer)
        self.save_timer = GLib.timeout_add(50 if immediately else 900, self.flush_save)

    def flush_save(self):
        if self.save_timer:
            GLib.source_remove(self.save_timer)
            self.save_timer = None
        session = self.editing
        if session is None:
            return False
        snapshot = self.editor_snapshot(session["buffer"], session["tags"], session["collections"])
        if snapshot == session["saved"] and not session["photo"]:
            return False
        if not snapshot[0].strip():
            return False  # Une note encore vide n'est pas publiée.
        session["saved"] = snapshot
        session["status"].set_text("Enregistrement…")
        vault, device = self.vault, self.settings["device"]

        def task():
            with session["lock"]:
                fields = {"kind": session["kind"], "text": snapshot[0], "tags": snapshot[1].split(","),
                          "collections": snapshot[2].split(",")}
                action = "create"
                if session["id"]:
                    fields.update(id=session["id"], trashed=False)
                    action = "save"
                photo = session["photo"]
                if photo:
                    fields["photo"] = photo
                reply = request(CORE, vault, device, action, **fields)
                session["id"] = reply["item"]["id"]
                if photo and session["photo"] == photo:
                    session["photo"] = None
                    Path(photo).unlink(missing_ok=True)
                return reply

        def done(future):
            self.saves_in_flight -= 1
            self.list_dirty = True
            try:
                reply = future.result()
                if self.editing is session:
                    session["status"].set_text("Enregistré")
                    self.selected = self.row_key(reply["item"])
            except Exception as error:
                session["saved"] = None
                if self.editing is session:
                    session["status"].set_text(f"Non enregistré : {error}")
                else:
                    self.notify(f"La dernière modification n’a pas été enregistrée : {error}", Gtk.MessageType.ERROR)
            if self.editing is None and self.saves_in_flight == 0 and self.list_dirty:
                self.list_dirty = False
                self.reload()
            return False

        self.saves_in_flight += 1
        self.save_worker.submit(task).add_done_callback(lambda future: GLib.idle_add(done, future))
        return False

    def trash_edited(self, item):
        session = self.editing
        self.flush_save()
        self.editing = None
        vault, device = self.vault, self.settings["device"]

        def trash():
            # Dans la file des écritures : après la dernière révision publiée,
            # jamais en concurrence avec elle.
            current = dict(item, id=session["id"]) if session and session["id"] else item
            return request(CORE, vault, device, "trash", **self.fields(current))

        def done(future):
            try:
                future.result()
            except Exception as error:
                self.notify(str(error), Gtk.MessageType.ERROR)
            self.show_timeline()
            self.reload()
            return False

        self.save_worker.submit(trash).add_done_callback(lambda future: GLib.idle_add(done, future))

    def show_detail(self, result=None, item=None):
        for child in self.detail.get_children():
            child.destroy()

        def add(widget):
            self.detail.pack_start(widget, False, False, 0)

        back = Gtk.Button()
        back.set_relief(Gtk.ReliefStyle.NONE)
        back.get_style_context().add_class("back")
        back.add(self.nav_content("go-previous-symbolic", self.filter_title()))
        back.set_halign(Gtk.Align.START)
        back.connect("clicked", lambda _: self.show_timeline())
        add(back)
        if not result:
            self.detail.show_all()
            return
        add(label(f"{LABELS[item['group']]}  ·  {self.date_label(item)}", "meta"))
        heading = label(item["title"], "headline")
        heading.set_line_wrap(True)
        heading.set_max_width_chars(48)
        heading.set_selectable(True)
        add(heading)
        categories = "  ·  ".join([*item["tags"], *item["collections"]])
        if categories:
            add(label(categories, "meta"))

        actions = Gtk.Box(spacing=8)
        add(actions)

        def action(title, callback):
            self.button(lambda widget: actions.pack_start(widget, False, False, 0), title, callback)

        if item["deleted"]:
            action("Restaurer", lambda: self.change("restore", item))
        else:
            action("Modifier", lambda: self.edit(item["group"], item, result))
            action("Corbeille", lambda: self.confirm("Mettre cet élément à la corbeille ?") and self.change("trash", item))
        if item.get("audio"):
            action("Écouter / arrêter", lambda: self.play(item["audio"]))
        elif result.get("audio"):
            action("Écouter / arrêter", lambda: self.journal_audio(item))
        if item["conflict"]:
            action("Garder cette version…", lambda: self.resolve(item))

        for photo in result.get("photos", []):
            loader = GdkPixbuf.PixbufLoader.new()
            loader.connect("size-prepared", self.limit_image, 560)
            try:
                loader.write(base64.b64decode(photo))
                loader.close()
                picture = Gtk.Image.new_from_pixbuf(loader.get_pixbuf())
                picture.set_halign(Gtk.Align.START)
                add(picture)
            except GLib.Error:
                add(label("La photo n’a pas pu être affichée.", "meta"))

        shown = result.get("preview") or result["text"]
        first, _, rest = shown.partition("\n")
        if first.strip() == item["title"].strip():
            shown = rest.lstrip("\n")
        body = label(shown)
        body.set_line_wrap(True)
        body.set_selectable(True)
        body.set_max_width_chars(65)
        add(body)
        if result.get("transcript"):
            add(label("Transcription", "row-title"))
            transcript = label("\n".join(segment["text"] for segment in result["transcript"]))
            transcript.set_line_wrap(True)
            transcript.set_selectable(True)
            transcript.set_max_width_chars(65)
            add(transcript)
        if not item["deleted"] and (item.get("audio") or result.get("audio")):
            transcribe = self.button(add, "Revoir la transcription…" if result.get("transcript") else "Transcrire l’audio…",
                                     lambda: show_transcription(self, item, result, SHARE / "ggml-base-q5_1.bin",
                                                                CORE.with_name("whisper-cli")))
            transcribe.set_halign(Gtk.Align.START)
        for attachment in result.get("media", []):
            self.button(add, f"Enregistrer {attachment['filename']}…",
                        lambda attachment=attachment: self.save_media(item, attachment))
        self.detail.show_all()

    @staticmethod
    def limit_image(loader, width, height, limit):
        scale = min(1, limit / max(width, height))
        loader.set_size(max(1, round(width * scale)), max(1, round(height * scale)))

    def edit(self, kind, item=None, result=None, prefill=""):
        if self.pending or self.recording:
            return
        if kind != "memo":
            self.flush_save()
            self.selected = None
            self.stack.set_visible_child_name("detail")
            self.show_editor(kind, item, result, prefill)
            return
        dialog = Gtk.Dialog(title="Modifier" if item else "Écrire", transient_for=self, modal=True)
        dialog.set_default_size(660, 530)
        dialog.add_button("Annuler", Gtk.ResponseType.CANCEL)
        save = dialog.add_button("Enregistrer", Gtk.ResponseType.OK)
        save.get_style_context().add_class("suggested-action")
        box = dialog.get_content_area()
        box.set_border_width(16)
        box.set_spacing(9)

        def field(hint, text):
            entry = Gtk.Entry(placeholder_text=hint, text=text)
            box.pack_start(entry, False, False, 0)
            return entry

        item = item or {}
        title = field("Titre du mémo", item["title"]) if kind == "memo" else None
        tags = field("Tags séparés par des virgules", ", ".join(item.get("tags", [])))
        collections = field("Collections séparées par des virgules", ", ".join(item.get("collections", []))) if kind != "memo" else None
        text = Gtk.TextView(wrap_mode=Gtk.WrapMode.WORD_CHAR, top_margin=10, bottom_margin=10, left_margin=10, right_margin=10)
        buffer = text.get_buffer()
        original = result["text"] if result else ""
        buffer.set_text(original or prefill)
        box.pack_start(scroller(text), True, True, 0)
        photo = None
        if kind != "memo":
            photo = Gtk.FileChooserButton(title="Joindre ou remplacer la photo")
            images = Gtk.FileFilter()
            images.set_name("Images")
            images.add_pixbuf_formats()
            photo.add_filter(images)
            box.pack_start(photo, False, False, 0)
        error = label("", "error")
        box.pack_start(error, False, False, 0)
        dialog.show_all()
        text.grab_focus()

        def respond(_, response):
            if self.pending:
                return
            body = buffer.get_text(*buffer.get_bounds(), False)
            if response != Gtk.ResponseType.OK:
                changed = body != original or (title and title.get_text() != item["title"])
                changed = changed or tags.get_text() != ", ".join(item.get("tags", []))
                changed = changed or (collections and collections.get_text() != ", ".join(item.get("collections", [])))
                if (changed or (photo and photo.get_filename())) and not self.confirm("Abandonner les modifications ?"):
                    return
                dialog.destroy()
                return
            if not (title.get_text().strip() if title else body.strip()):
                error.set_text("Saisissez un titre." if title else "Saisissez du texte.")
                return

            fields = self.fields(item) if item else {"kind": kind}
            fields.update(text=body, tags=tags.get_text().split(","))
            if title:
                fields["title"] = title.get_text()
            if collections:
                fields["collections"] = collections.get_text().split(",")
            try:
                if photo and photo.get_filename():
                    pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(photo.get_filename(), 1800, 1800, True)
                    path = Path(self.temp.name) / f"{uuid4().hex}.jpg"
                    pixbuf.savev(str(path), "jpeg", ["quality"], ["88"])
                    fields["photo"] = str(path)
            except GLib.Error as failure:
                error.set_text(f"Impossible de lire la photo. {failure.message}")
                return

            def save_note():
                try:
                    return self.command("save" if item else "create", **fields)
                finally:
                    if "photo" in fields:
                        Path(fields["photo"]).unlink(missing_ok=True)

            def saved(reply):
                dialog.destroy()
                self.after_change(reply)

            def failed(failure):
                error.set_text(str(failure))
                dialog.set_sensitive(True)

            dialog.set_sensitive(False)
            self.run_job("Enregistrement…", save_note, saved, failed)

        error.set_line_wrap(True)
        dialog.connect("response", respond)
        dialog.connect("delete-event", lambda *_: (respond(dialog, Gtk.ResponseType.DELETE_EVENT), True)[1])

    def after_change(self, result):
        if result.get("message"):
            self.notify(result["message"], Gtk.MessageType.WARNING)
        item = result.get("item")
        selected = None
        if item and not item["deleted"]:
            kind, value = self.filter
            visible = (kind == "section" and value in {"all", item["group"]} or kind == "tag" and value in item["tags"]
                       or kind == "collection" and value in item["collections"])
            if not visible:
                self.filter = ("section", item["group"] if item["group"] in SECTIONS else "all")
            selected = self.row_key(item)
            self.stack.set_visible_child_name("detail")
        else:
            self.show_timeline()
        self.reload(selected=selected)

    def change(self, action, item):
        self.run_job("Modification du coffre…", lambda: self.command(action, **self.fields(item)), self.after_change)

    def resolve(self, item):
        parents = [row["id"] for row in self.items if row.get("entryID") == item["entryID"]]
        if len(parents) > 1 and self.confirm(f"Garder la version affichée parmi ces {len(parents)} versions ?"):
            self.run_job("Résolution du conflit…",
                         lambda: self.command("resolve", parents=parents, **self.fields(item)), self.after_change)

    def choose(self, title, action, name=None):
        chooser = Gtk.FileChooserNative.new(title, self, action, "Sélectionner", "Annuler")
        if name:
            chooser.set_current_name(name)
        path = chooser.get_filename() if chooser.run() == Gtk.ResponseType.ACCEPT else None
        chooser.destroy()
        return path

    def vault_subtitle(self):
        if self.registry and len(self.registry.vaults) > 1:
            return self.registry.active["name"]
        return None

    def rebuild_vault_menu(self):
        for child in self.vault_menu.get_children():
            self.vault_menu.remove(child)
        if getattr(self, "vault_button", None) is not None:
            if self.vault_button.get_child() is not None:
                self.vault_button.get_child().destroy()
            content = self.nav_content("drive-harddisk-symbolic", self.registry.active["name"] if self.registry else self.vault.name)
            content.pack_end(Gtk.Image.new_from_icon_name("pan-down-symbolic", Gtk.IconSize.MENU), False, False, 0)
            self.vault_button.add(content)
            self.vault_button.show_all()

        def add(label, callback, sensitive=True, parent=None):
            item = Gtk.MenuItem(label=label)
            item.set_sensitive(sensitive)
            item.connect("activate", lambda _: callback() if not self.pending and not self.recording else None)
            (parent or self.vault_menu).append(item)

        if self.registry:
            active = self.registry.active["id"]
            for vault in self.registry.vaults:
                item = Gtk.CheckMenuItem(label=vault["name"], active=same(vault["id"], active))
                item.set_draw_as_radio(True)
                item.connect("activate", lambda _, identifier=vault["id"]: self.open_vault(identifier)
                             if not self.pending and not self.recording else None)
                self.vault_menu.append(item)
            self.vault_menu.append(Gtk.SeparatorMenuItem())
        add("Ajouter un coffre…", self.choose_vault)
        if self.registry:
            add("Renommer le coffre ouvert…", self.rename_vault)
            others = [vault for vault in self.registry.vaults if not same(vault["id"], self.registry.active["id"])]
            remove = Gtk.MenuItem(label="Retirer de la liste")
            remove.set_sensitive(bool(others))
            submenu = Gtk.Menu()
            for vault in others:
                add(vault["name"], lambda identifier=vault["id"]: self.remove_vault(identifier), parent=submenu)
            remove.set_submenu(submenu)
            self.vault_menu.append(remove)
        self.vault_menu.show_all()

    def ask_name(self, title, value):
        dialog, box = dialog_for(self, title, 420)
        dialog.add_button("Valider", Gtk.ResponseType.OK)
        dialog.set_default_response(Gtk.ResponseType.OK)
        field = entry(box, "Nom du coffre", value)
        dialog.show_all()
        name = field.get_text() if dialog.run() == Gtk.ResponseType.OK else None
        dialog.destroy()
        return name

    def choose_vault(self):
        path = self.choose("Sélectionner la racine du coffre", Gtk.FileChooserAction.SELECT_FOLDER)
        if not path:
            return
        identifier = None
        if self.registry:
            known = next((vault for vault in self.registry.vaults if self.registry.root(vault) == Path(path).resolve()), None)
            if known:
                identifier = known["id"]
            else:
                name = self.ask_name("Ajouter un coffre", Path(path).name)
                if name is None:
                    return
                try:
                    identifier = self.registry.add(name, path)
                except (RegistryError, OSError) as error:
                    self.notify(str(error), Gtk.MessageType.ERROR)
                    return
        self.open_vault(identifier, path)

    def open_vault(self, identifier, path=None):
        if identifier and self.registry:
            if same(identifier, self.registry.active["id"]) and path is None:
                self.rebuild_vault_menu()  # remet la coche que le clic a retirée
                return
            path = str(self.registry.root(next(v for v in self.registry.vaults if same(v["id"], identifier))))

        def opened(result):
            self.stop_playback()
            if identifier and self.registry:
                self.registry.activate(identifier)
            self.vault = Path(path)
            self.settings["vault"] = path
            self.write_settings()
            self.selected = None
            self.header.set_subtitle(self.vault_subtitle())
            self.rebuild_vault_menu()
            self.loaded(result, None)
            self.agenda.load(online=False)

        def failed(error):
            # L'ancien coffre reste ouvert ; la coche du menu revient à lui.
            self.rebuild_vault_menu()
            self.notify(str(error), Gtk.MessageType.ERROR)

        self.run_job("Ouverture du coffre…", lambda: request(CORE, path, self.settings["device"], "refresh"), opened, failed)

    def rename_vault(self):
        name = self.ask_name("Renommer le coffre", self.registry.active["name"])
        if name is None:
            return
        try:
            self.registry.rename(self.registry.active["id"], name)
        except (RegistryError, OSError) as error:
            self.notify(str(error), Gtk.MessageType.ERROR)
            return
        self.header.set_subtitle(self.vault_subtitle())
        self.rebuild_vault_menu()

    def remove_vault(self, identifier):
        vault = next(v for v in self.registry.vaults if same(v["id"], identifier))
        if not self.confirm(f"Retirer « {vault['name']} » de la liste ? Ses fichiers restent dans {self.registry.root(vault)}."):
            return
        try:
            self.registry.remove(identifier)
        except (RegistryError, OSError) as error:
            self.notify(str(error), Gtk.MessageType.ERROR)
            return
        self.header.set_subtitle(self.vault_subtitle())
        self.rebuild_vault_menu()

    def export(self):
        path = self.choose("Dossier de destination de l’export", Gtk.FileChooserAction.SELECT_FOLDER)
        if path:
            self.run_job("Export en cours…", lambda: self.command("export", path=path),
                         lambda result: self.notify(f"{result['message']}\n\n{result['path']}"))

    def open_path(self, path):
        try:
            Gio.AppInfo.launch_default_for_uri(Path(path).as_uri(), None)
        except GLib.Error as error:
            self.notify(error.message, Gtk.MessageType.ERROR)

    def save_media(self, item, attachment):
        path = self.choose("Enregistrer la pièce jointe", Gtk.FileChooserAction.SAVE, attachment["filename"])
        if path:
            self.run_job("Copie de la pièce jointe…",
                         lambda: self.command("media", path=path, attachmentID=attachment["id"], **self.fields(item)),
                         lambda _: None)

    def journal_audio(self, item):
        if self.stop_playback():
            return
        path = str(Path(self.temp.name) / f"{uuid4().hex}.m4a")
        self.run_job("Préparation de l’audio…", lambda: self.command("media", path=path, **self.fields(item)),
                     lambda _: self.play(path, temporary=True))

    def play(self, path, temporary=False):
        if self.stop_playback():
            return
        log = tempfile.TemporaryFile()
        process = subprocess.Popen(
            ["ffplay", "-hide_banner", "-loglevel", "error", "-nodisp", "-autoexit", path],
            stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=log,
        )
        self.playback = process
        self.status.set_text("Lecture audio…")

        def finished():
            if process.poll() is None:
                return True
            if temporary:
                Path(path).unlink(missing_ok=True)
            if self.playback is process:
                self.playback = None
                self.status.set_text("")
                if process.returncode:
                    log.seek(0)
                    self.notify(log.read().decode(errors="replace").strip() or "Lecture audio impossible.", Gtk.MessageType.ERROR)
            log.close()
            return False

        GLib.timeout_add(250, finished)

    def stop_playback(self):
        process = self.playback
        if process is None:
            return False
        self.playback = None
        if process.poll() is None:
            process.terminate()
        self.status.set_text("")
        return True

    def import_audio(self):
        path = self.choose("Importer un fichier audio", Gtk.FileChooserAction.OPEN)
        if path:
            self.run_job("Import audio…", lambda: self.ingest(path, Path(path).stem), self.after_change)

    def ingest(self, source, title):
        with tempfile.TemporaryDirectory(dir=self.temp.name) as folder:
            output = str(Path(folder) / "audio.m4a")
            audio_command("ffmpeg", "-hide_banner", "-loglevel", "error", "-i", source,
                          "-map", "0:a:0", "-c:a", "aac", "-ac", "1", "-ar", "48000", "-b:a", "96k", output)
            duration = audio_command("ffprobe", "-v", "error", "-show_entries", "format=duration",
                                     "-of", "default=nw=1:nk=1", output).strip()
            try:
                seconds = float(duration)
            except ValueError:
                seconds = 0
            if not math.isfinite(seconds) or seconds < 0.001:
                raise RuntimeError("Aucun échantillon audio à enregistrer.")
            return self.command("ingest", path=output, title=title, durationMs=round(1000 * seconds))

    def record(self):
        if self.pending:
            return
        if self.recording:
            self.finish_recording()
            return
        self.stop_playback()
        captures = self.state / "Captures"
        captures.mkdir(exist_ok=True)
        path = captures / f"{datetime.now().strftime('%Y%m%d-%H%M%S')}-{uuid4().hex[:8]}.wav"
        log = tempfile.TemporaryFile()
        process = subprocess.Popen(
            ["ffmpeg", "-hide_banner", "-loglevel", "error", "-f", "pulse", "-i", "default",
             "-ac", "1", "-ar", "48000", str(path)], stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=log,
        )
        self.recording = (process, path, log)
        self.record_button.set_image(Gtk.Image.new_from_icon_name("media-playback-stop-symbolic", Gtk.IconSize.LARGE_TOOLBAR))
        self.record_button.set_tooltip_text("Arrêter l’enregistrement")
        self.record_button.get_style_context().add_class("recording")
        self.status.set_text("Capture du microphone en cours…")

        def watch():
            if self.recording is None or self.recording[0] is not process:
                return False
            if process.poll() is None:
                return True
            self.finish_recording()
            return False

        GLib.timeout_add(250, watch)

    def finish_recording(self):
        process, path, log = self.recording
        self.recording = None
        self.record_button.set_image(Gtk.Image.new_from_icon_name("audio-input-microphone-symbolic", Gtk.IconSize.LARGE_TOOLBAR))
        self.record_button.set_tooltip_text("Enregistrer la voix")
        self.record_button.get_style_context().remove_class("recording")

        def finish():
            with log:
                try:
                    process.communicate(input=b"q\n" if process.poll() is None else None, timeout=10)
                except subprocess.TimeoutExpired:
                    process.kill()
                    process.communicate()
                try:
                    if process.returncode:
                        log.seek(0)
                        raise RuntimeError(log.read().decode(errors="replace").strip() or "Microphone indisponible.")
                    result = self.ingest(str(path), None)
                except Exception as error:
                    if path.is_file() and path.stat().st_size:
                        raise RuntimeError(f"{error}\n\nCapture disponible dans {path}") from error
                    path.unlink(missing_ok=True)
                    raise
                path.unlink()
                return result

        self.run_job("Finalisation de l’enregistrement…", finish, self.after_change)

    def on_close(self, *_):
        if self.pending or self.recording:
            self.notify("Terminez l’opération en cours avant de fermer Envorenn.")
            return True
        self.stop_playback()
        self.flush_save()
        # Une écriture partie va au bout avant que l'application se ferme.
        self.save_worker.shutdown(wait=True)
        self.thumbnail_worker.shutdown(wait=False)
        self.worker.shutdown()
        self.temp.cleanup()
        return False


class Application(Gtk.Application):
    def __init__(self):
        super().__init__(application_id=APP_ID)

    def do_activate(self):
        window = self.get_active_window()
        if not window:
            css = Gtk.CssProvider()
            css.load_from_path(str(SHARE / "style.css"))
            Gtk.StyleContext.add_provider_for_screen(
                Gdk.Screen.get_default(), css, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION,
            )
            window = Window(self)
        window.present()


if __name__ == "__main__":
    os.umask(0o077)
    raise SystemExit(Application().run())
