#!/usr/bin/env python3
"""LinuxDoors Package Manager -- a Synaptic-style GTK3 app for browsing,
installing, and uninstalling packages from linuxdoors.com, either as
precompiled downloads or compiled locally from real source. Must run as
root (installing/uninstalling writes into the real system)."""
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk, GLib, Pango
import cairo
import os
import sys
import threading

sys.path.insert(0, "/usr/local/lib/linuxdoors-pkg")
import linuxdoors_pkg_backend as backend
# Real Debian .deb packages -- deployed by scripts/lfs_debtool_setup.sh into
# the same directory (must run before this script's own GUI is used, or
# this import fails). Used by the Debian-packages toggle below.
import deb_backend

CSS = b"""
window, .background {
    background-image: linear-gradient(to bottom, #1c1038, #0a0616);
    background-color: #1c1038;
}
.title { color: #fbeed2; font-weight: bold; font-size: 22px; }
.subtitle { color: #b8a4d8; font-size: 13px; }
.card {
    background-color: #201038;
    border-radius: 14px;
    border: 1px solid #3a2570;
}
button {
    border-radius: 8px;
    padding: 8px 16px;
    border: none;
    background-image: none;
    transition: background-color 150ms ease;
}
button.suggested-action {
    background-color: #e8c98a;
    background-image: none;
    color: #1c1038;
    font-weight: bold;
}
button.suggested-action label { color: #1c1038; }
button.suggested-action:hover { background-color: #f6d9a0; }
button.destructive-action {
    background-color: #c0392b;
    background-image: none;
    color: #fbeed2;
    font-weight: bold;
}
button.destructive-action label { color: #fbeed2; }
button.destructive-action:hover { background-color: #d9483a; }
button.flat-nav {
    background-color: #241246;
    background-image: none;
    color: #cdbdec;
    border: 1px solid #3a2570;
}
button.flat-nav label { color: #cdbdec; }
button.flat-nav:hover { background-color: #33205e; }
label { color: #fbeed2; }
/* Fallback for any plain/unclassed button (GTK's own stock dialog
   buttons from add_buttons()/add_button() -- e.g. the uninstall
   confirmation dialog's "Cancel", the error dialog's "OK") -- without
   this, the blanket `label` rule above (meant for text on this app's own
   dark card background) applies its light cream color to a button's
   default light/white chrome too, producing the "white button, barely-
   visible font" contrast bug. More specific than the bare `label` rule,
   less specific than the per-class rules above, so it only kicks in as a
   safe default. */
button label { color: #1c1038; }
/* Force our own entry colours over any host GTK theme (see the launcher
   script for the full note -- same class of "themed white entry hides the
   text" bug). background-image:none clears a themed gradient; the inner
   `entry text` node is set explicitly for GTK 3.20+. */
entry {
    background-image: none;
    background-color: #241246;
    color: #fbeed2;
    caret-color: #fbeed2;
    border-radius: 8px;
    border: 1px solid #3a2570;
    padding: 6px 10px;
}
entry text {
    color: #fbeed2;
    caret-color: #fbeed2;
    background-color: transparent;
}
entry text selection { background-color: #e8c98a; color: #1c1038; }
entry image, entry placeholder { color: #b8a4d8; }
treeview { background-color: #201038; color: #fbeed2; }
treeview:selected { background-color: #33205e; }
treeview header button { background-color: #241246; color: #cdbdec; border: none; }
/* Real bug, user-reported: "Package/Category/Status column headers should
   be light-colored against this dark background" -- same failure class as
   the earlier button-label bug (see CLAUDE.md): the button-level `color:`
   above only sets the DEFAULT/inherited color, but the header's own child
   GtkLabel is matched more directly by the `button label { color: #1c1038; }`
   fallback rule below (added earlier for GTK's own unclassed stock dialog
   buttons), so a direct match wins and the header text rendered in dark
   indigo on a dark purple background -- nearly invisible. Fixed with an
   explicit, more specific selector for this exact case. */
treeview header button label { color: #cdbdec; }
scrolledwindow, viewport { background-color: transparent; }
.pill-installed { color: #9ad38a; font-weight: bold; }
.pill-not-installed { color: #6c5a94; }
progressbar trough { background-color: #241246; border-radius: 8px; min-height: 10px; }
progressbar progress { background-color: #e8c98a; border-radius: 8px; min-height: 10px; }
/* Hover tooltips (package summary) and the right-click "Description"
   context menu -- same dark/gold palette as the rest of the app rather
   than GTK's plain default tooltip/menu chrome. */
tooltip {
    background-color: #201038;
    border: 1px solid #e8c98a;
    border-radius: 8px;
    padding: 6px;
}
tooltip label { color: #fbeed2; }
menu, .menu {
    background-color: #24123f;
    border: 1px solid #e8c98a;
    border-radius: 8px;
    padding: 4px;
}
menuitem { border-radius: 6px; padding: 6px 12px; }
menuitem label { color: #fbeed2; }
menuitem:hover { background-color: #3a2570; }
textview, textview text {
    background-color: #180c2c;
    color: #fbeed2;
}
"""

DOOR_FRAME = (0xfb / 255, 0xee / 255, 0xd2 / 255)
DOOR_OPENING = (0xf6 / 255, 0xd9 / 255, 0xa0 / 255)
DOOR_LEAF = (0x2c / 255, 0x18 / 255, 0x54 / 255)
DOOR_GOLD = (0xe8 / 255, 0xc9 / 255, 0x8a / 255)


def draw_door(_widget, cr, w, h):
    """Same crisp, no-blur door construction used everywhere else in this
    project (wallpaper, GRUB splash, the Phase 1.5 installer)."""
    sx, sy = w / 260.0, h / 330.0
    cr.save()
    cr.set_source_rgb(*DOOR_FRAME)
    cr.rectangle(20 * sx, 20 * sy, 220 * sx, 290 * sy)
    cr.fill()
    cr.set_source_rgb(*DOOR_OPENING)
    cr.rectangle(38 * sx, 38 * sy, 184 * sx, 272 * sy)
    cr.fill()
    cr.move_to(38 * sx, 38 * sy)
    cr.line_to(150 * sx, 50 * sy)
    cr.line_to(172 * sx, 325 * sy)
    cr.line_to(38 * sx, 310 * sy)
    cr.close_path()
    cr.set_source_rgb(*DOOR_LEAF)
    cr.fill_preserve()
    cr.set_source_rgb(*DOOR_GOLD)
    cr.set_line_width(3)
    cr.stroke()
    cr.arc(150 * sx, 190 * sy, 6 * sx, 0, 2 * 3.14159)
    cr.set_source_rgb(*DOOR_GOLD)
    cr.fill()
    cr.restore()
    return False


class ChoiceDialog(Gtk.Dialog):
    """'How would you like to install <name>?' -- precompiled vs source."""

    def __init__(self, parent, name):
        super().__init__(title=f"Install {name}", transient_for=parent, modal=True)
        self.set_default_size(440, 220)
        self.choice = None

        box = self.get_content_area()
        box.set_spacing(14)
        box.set_border_width(20)

        label = Gtk.Label(label=f"How would you like to install {name}?")
        label.get_style_context().add_class("title")
        label.set_line_wrap(True)
        box.pack_start(label, False, False, 0)

        precompiled_btn = Gtk.Button(label="Precompiled package (fast)")
        precompiled_btn.get_style_context().add_class("suggested-action")
        precompiled_btn.connect("clicked", self._choose, "precompiled")
        box.pack_start(precompiled_btn, False, False, 4)

        source_btn = Gtk.Button(label="Build from source (compiles on this computer)")
        source_btn.get_style_context().add_class("flat-nav")
        source_btn.connect("clicked", self._choose, "source")
        box.pack_start(source_btn, False, False, 0)

        cancel_btn = Gtk.Button(label="Cancel")
        cancel_btn.get_style_context().add_class("flat-nav")
        cancel_btn.connect("clicked", lambda *_: self.response(Gtk.ResponseType.CANCEL))
        box.pack_start(cancel_btn, False, False, 8)

        self.show_all()

    def _choose(self, _button, choice):
        self.choice = choice
        self.response(Gtk.ResponseType.OK)


class DescriptionDialog(Gtk.Dialog):
    """Right-click "Description" -- shows a package's full description in
    a scrollable, read-only text area. The main window's own table never
    shows description text at all (that column only ever powers search
    filtering); the Find More dialog's Description column shows it but
    ellipsized to one line. Both get this dialog as the real, full-text
    view."""

    def __init__(self, parent, name, version, extra, status, description):
        super().__init__(title=f"{name} {version}", transient_for=parent, modal=True)
        self.set_default_size(480, 360)

        box = self.get_content_area()
        box.set_spacing(10)
        box.set_border_width(16)

        header = Gtk.Label(label=f"{name} {version}", xalign=0)
        header.get_style_context().add_class("title")
        header.set_line_wrap(True)
        box.pack_start(header, False, False, 0)

        meta = Gtk.Label(label=f"{extra}   —   {status}", xalign=0)
        meta.get_style_context().add_class("subtitle")
        box.pack_start(meta, False, False, 0)

        scroller = Gtk.ScrolledWindow()
        scroller.set_vexpand(True)
        scroller.set_shadow_type(Gtk.ShadowType.IN)
        text_view = Gtk.TextView()
        text_view.set_editable(False)
        text_view.set_cursor_visible(False)
        text_view.set_wrap_mode(Gtk.WrapMode.WORD)
        text_view.set_left_margin(10)
        text_view.set_right_margin(10)
        text_view.set_top_margin(10)
        text_view.set_bottom_margin(10)
        text_view.get_buffer().set_text(description.strip() if description else "(no description available)")
        scroller.add(text_view)
        box.pack_start(scroller, True, True, 0)

        close_btn = Gtk.Button(label="Close")
        close_btn.get_style_context().add_class("suggested-action")
        close_btn.connect("clicked", lambda _b: self.response(Gtk.ResponseType.CLOSE))
        box.pack_start(close_btn, False, False, 0)

        self.show_all()


def _row_context_menu(parent_window, get_row_data_fn):
    """Shared by both the main window's tree and FindMoreDialog's --
    right-click anywhere on a row shows this single-item menu; "Description"
    opens a DescriptionDialog for whichever row get_row_data_fn() reports
    (the row under the pointer at click time, already selected by the
    caller's own button-press-event handler before this runs)."""
    menu = Gtk.Menu()
    item = Gtk.MenuItem(label="Description")

    def on_activate(_item):
        data = get_row_data_fn()
        if data is None:
            return
        dialog = DescriptionDialog(parent_window, *data)
        dialog.run()
        dialog.destroy()

    item.connect("activate", on_activate)
    menu.append(item)
    menu.show_all()
    return menu


def _truncate(text, limit=220):
    text = (text or "").strip()
    if not text:
        return "(no description available)"
    return text if len(text) <= limit else text[:limit].rstrip() + "…"


class ProgressDialog(Gtk.Dialog):
    def __init__(self, parent, title):
        super().__init__(title=title, transient_for=parent, modal=True)
        self.set_default_size(440, 140)
        self.set_deletable(False)
        box = self.get_content_area()
        box.set_spacing(12)
        box.set_border_width(20)

        self.status_label = Gtk.Label(label="Starting...")
        self.status_label.set_line_wrap(True)
        box.pack_start(self.status_label, False, False, 0)

        self.spinner = Gtk.Spinner()
        self.spinner.start()
        box.pack_start(self.spinner, False, False, 0)

        self.show_all()

    def set_status(self, msg):
        GLib.idle_add(self.status_label.set_text, msg)


class FindMoreDialog(Gtk.Dialog):
    """"Find More..." -- only shown in Debian view. Searches Debian's
    real, full live package index (linuxdoors.com's own cached copy,
    hundreds of thousands of real packages -- far more than the small
    curated/staged catalog the main window's own list shows) via
    search_all_debian(). Double-clicking a result just starts the
    ordinary install flow -- deb_backend.install() already transparently
    requests staging via linuxdoors.com as part of its own fallback chain
    when a name isn't in the curated catalog yet, so no separate "stage"
    step or button is needed here."""

    def __init__(self, parent, suite):
        super().__init__(title="Find More Debian Packages", transient_for=parent, modal=True)
        self.parent_window = parent
        self.suite = suite
        # At least as wide as the main window (880) -- user-reported: this
        # dialog felt cramped next to it.
        self.set_default_size(900, 560)

        box = self.get_content_area()
        box.set_spacing(10)
        box.set_border_width(16)

        entry_row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8)
        self.entry = Gtk.SearchEntry(placeholder_text="Search all real Debian packages...")
        self.entry.connect("activate", lambda _e: self._do_search())
        entry_row.pack_start(self.entry, True, True, 0)
        search_btn = Gtk.Button(label="Search")
        search_btn.get_style_context().add_class("suggested-action")
        search_btn.connect("clicked", lambda _b: self._do_search())
        entry_row.pack_start(search_btn, False, False, 0)
        box.pack_start(entry_row, False, False, 0)

        self.status_label = Gtk.Label(
            label="Search Debian's real, full package index -- far more packages "
                  "than the curated catalog above.",
            xalign=0,
        )
        self.status_label.set_line_wrap(True)
        box.pack_start(self.status_label, False, False, 0)

        scroller = Gtk.ScrolledWindow()
        scroller.set_vexpand(True)
        box.pack_start(scroller, True, True, 0)

        self.list_store = Gtk.ListStore(str, str, str, str)  # name, version, description, status
        self.tree = Gtk.TreeView(model=self.list_store)
        for i, col_title in enumerate(["Package", "Version", "Description", "Status"]):
            renderer = Gtk.CellRendererText()
            if i == 2:
                renderer.set_property("ellipsize", Pango.EllipsizeMode.END)
            col = Gtk.TreeViewColumn(col_title, renderer, text=i)
            col.set_resizable(True)
            # A plain Gtk.ListStore (unlike MainWindow's filtered/sorted
            # model, which needs a TreeModelSort wrapper -- see the
            # comment on MainWindow's own columns below) implements
            # GtkTreeSortable natively, so set_sort_column_id works
            # directly here with no extra model wrapping needed.
            col.set_clickable(True)
            col.set_sort_column_id(i)
            self.tree.append_column(col)
        self.tree.connect("row-activated", self._on_row_activated)
        self.tree.connect("button-press-event", self._on_button_press)
        self.tree.set_has_tooltip(True)
        self.tree.connect("query-tooltip", self._on_query_tooltip)
        scroller.add(self.tree)

        close_btn = Gtk.Button(label="Close")
        close_btn.connect("clicked", lambda _b: self.response(Gtk.ResponseType.CLOSE))
        box.pack_start(close_btn, False, False, 0)

        self.show_all()

    def _do_search(self):
        query = self.entry.get_text().strip()
        if not query:
            return
        self.status_label.set_text("Searching linuxdoors.com...")
        self.list_store.clear()

        def worker():
            try:
                results = deb_backend.search_all_debian(query, self.suite)
                GLib.idle_add(self._populate, results, None)
            except deb_backend.DebToolError as exc:
                GLib.idle_add(self._populate, [], str(exc))

        threading.Thread(target=worker, daemon=True).start()

    def _populate(self, results, error):
        self.list_store.clear()
        if error:
            self.status_label.set_text(f"Search failed: {error}")
            return
        if not results:
            self.status_label.set_text("No matches.")
            return
        for r in results:
            status = "Staged (installable now)" if r.get("already_staged") else "Not staged yet"
            self.list_store.append([r["name"], r.get("version", ""), r.get("description", ""), status])
        self.status_label.set_text(f"{len(results)} match(es). Double-click one to install it.")

    def _on_row_activated(self, tree, path, _column):
        model = tree.get_model()
        it = model.get_iter(path)
        name = model[it][0]
        version = model[it][1]
        already_staged = model[it][3].startswith("Staged")

        confirm = Gtk.MessageDialog(
            transient_for=self, modal=True,
            message_type=Gtk.MessageType.QUESTION,
            text=f"Install {name} {version}?",
        )
        if already_staged:
            confirm.format_secondary_text("This package is already staged and installable now.")
        else:
            confirm.format_secondary_text(
                "This package isn't staged yet -- installing it will first ask "
                "linuxdoors.com to fetch and stage it for real (this can take a "
                "while), then install it. It stays available for every future "
                "install after that, not just this one."
            )
        confirm.add_buttons("Cancel", Gtk.ResponseType.CANCEL, "Install", Gtk.ResponseType.OK)
        ok_btn = confirm.get_widget_for_response(Gtk.ResponseType.OK)
        ok_btn.get_style_context().add_class("suggested-action")
        response = confirm.run()
        confirm.destroy()
        if response != Gtk.ResponseType.OK:
            return

        self.parent_window._run_with_progress(
            f"Installing {name}",
            lambda progress: deb_backend.install(name, progress),
        )
        self.response(Gtk.ResponseType.CLOSE)

    def _on_button_press(self, tree, event):
        if event.button != 3:
            return False
        result = tree.get_path_at_pos(int(event.x), int(event.y))
        if result is None:
            return False
        path, _column, _cx, _cy = result
        tree.set_cursor(path)

        def get_row_data():
            model = tree.get_model()
            it = model.get_iter(path)
            return (model[it][0], model[it][1], f"Suite: {self.suite}", model[it][3], model[it][2])

        menu = _row_context_menu(self, get_row_data)
        menu.popup_at_pointer(event)
        return True

    def _on_query_tooltip(self, tree, x, y, _keyboard_mode, tooltip):
        result = tree.get_path_at_pos(x, y)
        if result is None:
            return False
        path, _column, _cx, _cy = result
        model = tree.get_model()
        it = model.get_iter(path)
        name, description = model[it][0], model[it][2]
        tooltip.set_text(f"{name}\n{_truncate(description)}")
        tree.set_tooltip_row(tooltip, path)
        return True


class MainWindow(Gtk.Window):
    def __init__(self):
        super().__init__(title="LinuxDoors Package Manager")
        self.set_default_size(880, 560)
        self.viewing_debian = False
        self.debian_suite = "trixie"

        provider = Gtk.CssProvider()
        provider.load_from_data(CSS)
        Gtk.StyleContext.add_provider_for_screen(
            Gdk.Screen.get_default(), provider,
            Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION,
        )

        outer = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)
        self.add(outer)

        header = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=12)
        header.set_border_width(16)
        door = Gtk.DrawingArea()
        door.set_size_request(40, 50)
        door.connect("draw", lambda w, cr: draw_door(w, cr, 40, 50))
        header.pack_start(door, False, False, 0)

        title_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        title = Gtk.Label(label="LinuxDoors Package Manager", xalign=0)
        title.get_style_context().add_class("title")
        subtitle = Gtk.Label(
            label="Double-click a package to install or uninstall it.",
            xalign=0,
        )
        subtitle.get_style_context().add_class("subtitle")
        title_box.pack_start(title, False, False, 0)
        title_box.pack_start(subtitle, False, False, 0)
        header.pack_start(title_box, True, True, 0)

        self.search_entry = Gtk.SearchEntry(placeholder_text="Search packages...")
        self.search_entry.set_size_request(260, -1)
        self.search_entry.connect("search-changed", self._on_search_changed)
        header.pack_end(self.search_entry, False, False, 0)

        refresh_btn = Gtk.Button(label="Refresh")
        refresh_btn.get_style_context().add_class("flat-nav")
        refresh_btn.connect("clicked", lambda _b: self._refresh_thread())
        header.pack_end(refresh_btn, False, False, 0)

        # Starts unpressed/showing the LinuxDoors catalog, so its initial
        # label matches that -- see _on_debian_toggle for the live switch.
        self.debian_toggle_btn = Gtk.ToggleButton(label="LinuxDoors Packages")
        self.debian_toggle_btn.get_style_context().add_class("flat-nav")
        self.debian_toggle_btn.connect("toggled", self._on_debian_toggle)
        header.pack_end(self.debian_toggle_btn, False, False, 0)

        # Only meaningful in Debian view -- the curated catalog above is a
        # small, already-staged subset; this searches Debian's real, full
        # live index (linuxdoors.com's own cached copy, hundreds of
        # thousands of packages) via search_all_debian(). Hidden by
        # default since the initial view is LinuxDoors packages -- see
        # _on_debian_toggle for the show/hide.
        self.find_more_btn = Gtk.Button(label="Find More...")
        self.find_more_btn.get_style_context().add_class("flat-nav")
        self.find_more_btn.connect("clicked", lambda _b: self._open_find_more())
        self.find_more_btn.set_no_show_all(True)
        self.find_more_btn.hide()
        header.pack_end(self.find_more_btn, False, False, 0)

        outer.pack_start(header, False, False, 0)

        card = Gtk.Frame()
        card.get_style_context().add_class("card")
        card.set_margin_start(16)
        card.set_margin_end(16)
        card.set_margin_bottom(16)
        outer.pack_start(card, True, True, 0)

        scroller = Gtk.ScrolledWindow()
        scroller.set_border_width(4)
        card.add(scroller)

        self.store = Gtk.ListStore(str, str, str, str, str, str)  # name, version, category, description, status, status_color
        self.filter_model = self.store.filter_new()
        self.filter_model.set_visible_func(self._filter_visible)
        # Real gap, user-reported: clicking a column header did nothing --
        # GtkTreeViewColumn.set_sort_column_id() only works when the model
        # actually attached to the TreeView implements GtkTreeSortable.
        # Gtk.ListStore does, but the plain Gtk.TreeModelFilter wrapping it
        # (needed for the search box) does NOT, so every set_sort_column_id()
        # call below was a silent no-op. Fixed by inserting a TreeModelSort
        # on top of the filter -- it does implement GtkTreeSortable and
        # delegates comparisons down through the filter to the real store,
        # and it's what gives click-to-sort-ascending / click-again-to-
        # toggle-descending for free, no extra signal wiring needed.
        self.sort_model = Gtk.TreeModelSort(model=self.filter_model)
        self.tree = Gtk.TreeView(model=self.sort_model)
        scroller.add(self.tree)

        # store columns: 0=name 1=version 2=category 3=description 4=status
        # 5=status_color -- the visible "Status" column shows store column 4
        # (Installed/Not installed), not 3 (the description text, which is
        # only used for search filtering, never displayed directly).
        columns = [("Package", 0), ("Version", 1), ("Category", 2), ("Status", 4)]
        for i, (header_text, store_col) in enumerate(columns):
            renderer = Gtk.CellRendererText()
            if i == 0:
                renderer.set_property("ellipsize", Pango.EllipsizeMode.END)
            col = Gtk.TreeViewColumn(header_text, renderer, text=store_col)
            col.set_resizable(True)
            col.set_clickable(True)
            col.set_sort_column_id(store_col)
            if store_col == 4:
                col.add_attribute(renderer, "foreground", 5)
            self.tree.append_column(col)

        self.tree.connect("row-activated", self._on_row_activated)
        self.tree.connect("button-press-event", self._on_button_press)
        self.tree.set_has_tooltip(True)
        self.tree.connect("query-tooltip", self._on_query_tooltip)

        self._refresh_thread()

    def _filter_visible(self, model, it, _data):
        query = self.search_entry.get_text().lower().strip()
        if not query:
            return True
        name = (model[it][0] or "").lower()
        desc = (model[it][3] or "").lower()
        return query in name or query in desc

    def _on_search_changed(self, _entry):
        self.filter_model.refilter()

    def _on_debian_toggle(self, btn):
        self.viewing_debian = btn.get_active()
        # Real bug, user-reported: this button's label was hardcoded to
        # always read "Debian Packages" regardless of which view was
        # actually showing -- it should describe what's CURRENTLY listed
        # (so it reads "LinuxDoors Packages" while viewing the LinuxDoors
        # catalog, and "Debian Packages" while viewing the Debian one),
        # not a fixed destination label.
        btn.set_label("Debian Packages" if self.viewing_debian else "LinuxDoors Packages")
        if self.viewing_debian:
            self.find_more_btn.show()
        else:
            self.find_more_btn.hide()
        self.subtitle_debian_hint()
        self._refresh_thread()

    def _open_find_more(self):
        dialog = FindMoreDialog(self, self.debian_suite)
        dialog.run()
        dialog.destroy()
        self._refresh_thread()

    def subtitle_debian_hint(self):
        # Cheap, no dedicated label needed -- reuse the window title bar to
        # make the current mode obvious at a glance.
        self.set_title(
            "LinuxDoors Package Manager -- Debian packages (best-effort)"
            if self.viewing_debian else "LinuxDoors Package Manager"
        )

    def _refresh_thread(self):
        """Also the GUI's answer to `pkg update` -- the Refresh button
        calls this directly, and both it and the CLI command are backed by
        the exact same backend.list_upgradable() definition of "upgradable"
        (see that function's own docstring), just rendered differently: a
        redrawn table here, a printed list there. In Debian mode, pulls
        from linuxdoors.com's curated Debian catalog instead (see
        deb_backend.catalog_packages) -- upgrade tracking doesn't apply
        there yet (deb_backend has no version-upgrade concept, matching
        its own deliberately install-only scope for this first pass).
        """
        viewing_debian = self.viewing_debian

        def worker():
            try:
                if viewing_debian:
                    packages = deb_backend.catalog_packages(self.debian_suite)
                    upgradable_names = set()
                else:
                    packages = backend.list_packages()
                    upgradable_names = {u["name"] for u in backend.list_upgradable(packages)}
            except Exception as exc:
                GLib.idle_add(self._show_error, f"Could not load package list: {exc}")
                return
            GLib.idle_add(self._populate, packages, upgradable_names, viewing_debian)

        threading.Thread(target=worker, daemon=True).start()

    def _populate(self, packages, upgradable_names, viewing_debian):
        self.store.clear()
        self._packages_by_name = {}
        self._upgradable_names = upgradable_names
        for pkg in packages:
            self._packages_by_name[pkg["name"]] = pkg
            if viewing_debian:
                installed = deb_backend.is_installed(pkg["name"])
                status, color = ("Installed", "#9ad38a") if installed else ("Not installed", "#6c5a94")
                category = pkg.get("suite", self.debian_suite)
            else:
                installed = backend.is_installed(pkg["name"])
                if pkg["name"] in upgradable_names:
                    status, color = "Upgrade available", "#e8c98a"
                elif installed:
                    status, color = "Installed", "#9ad38a"
                else:
                    status, color = "Not installed", "#6c5a94"
                category = pkg["category"]
            self.store.append([
                pkg["name"], pkg["version"], category,
                pkg.get("description", ""), status, color,
            ])

    def _on_row_activated(self, tree, path, _column):
        model = tree.get_model()
        it = model.get_iter(path)
        name = model[it][0]
        pkg = self._packages_by_name.get(name)
        if pkg is None:
            return

        if self.viewing_debian:
            if deb_backend.is_installed(name):
                self._confirm_debian_uninstall(pkg)
            else:
                self._start_debian_install(pkg)
            return

        if backend.is_installed(name):
            manifest = backend.installed_manifest(name)
            if name in self._upgradable_names:
                self._confirm_upgrade(pkg, manifest)
            elif manifest and manifest.get("preinstalled"):
                self._show_base_package_notice(pkg)
            else:
                self._confirm_uninstall(pkg)
        else:
            self._start_install(pkg)

    def _on_button_press(self, tree, event):
        if event.button != 3:
            return False
        result = tree.get_path_at_pos(int(event.x), int(event.y))
        if result is None:
            return False
        path, _column, _cx, _cy = result
        tree.set_cursor(path)

        def get_row_data():
            model = tree.get_model()
            it = model.get_iter(path)
            name, version, category, description, status = (
                model[it][0], model[it][1], model[it][2], model[it][3], model[it][4]
            )
            pkg = self._packages_by_name.get(name)
            if pkg:
                description = pkg.get("description") or description
                category = pkg.get("category") or pkg.get("suite") or category
            label = "Suite" if self.viewing_debian else "Category"
            return (name, version, f"{label}: {category}", status, description)

        menu = _row_context_menu(self, get_row_data)
        menu.popup_at_pointer(event)
        return True

    def _on_query_tooltip(self, tree, x, y, _keyboard_mode, tooltip):
        result = tree.get_path_at_pos(x, y)
        if result is None:
            return False
        path, _column, _cx, _cy = result
        model = tree.get_model()
        it = model.get_iter(path)
        name = model[it][0]
        pkg = self._packages_by_name.get(name)
        description = (pkg.get("description") if pkg else None) or model[it][3]
        tooltip.set_text(f"{name}\n{_truncate(description)}")
        tree.set_tooltip_row(tooltip, path)
        return True

    def _confirm_debian_uninstall(self, pkg):
        dialog = Gtk.MessageDialog(
            transient_for=self, modal=True,
            message_type=Gtk.MessageType.QUESTION,
            text=f"Uninstall {pkg['name']}?",
        )
        dialog.format_secondary_text(
            "This removes the files this Debian-bridge install recorded for "
            f"{pkg['name']}. Any file still needed by another installed "
            "Debian package is left in place."
        )
        dialog.add_buttons(
            "Cancel", Gtk.ResponseType.CANCEL,
            "Uninstall", Gtk.ResponseType.OK,
        )
        ok_btn = dialog.get_widget_for_response(Gtk.ResponseType.OK)
        ok_btn.get_style_context().add_class("destructive-action")
        response = dialog.run()
        dialog.destroy()
        if response == Gtk.ResponseType.OK:
            self._run_with_progress(
                f"Uninstalling {pkg['name']}",
                lambda progress: deb_backend.uninstall(pkg["name"], progress),
            )

    def _start_debian_install(self, pkg):
        # Same precompiled-vs-source choice real LinuxDoors packages
        # already offer (reuses the exact same ChoiceDialog class) --
        # only shown when this Debian package actually has a staged
        # source-build kit (pkg["has_source_build"], from
        # /api/debian-packages); otherwise just confirm the precompiled
        # install, same as before, since offering "Build from source"
        # with nothing staged to build from would just fail.
        #
        # The "keep existing files" checkbox below is Debian-bridge-only
        # (appended to whichever confirmation dialog is shown here,
        # rather than built into the shared ChoiceDialog class) -- a real
        # LinuxDoors package's own destdir never overlaps another
        # package's files the way a Debian package's shared libs can, so
        # this choice has no meaning there.
        if pkg.get("has_source_build"):
            dialog = ChoiceDialog(self, pkg["name"])
            keep_existing_check = Gtk.CheckButton(
                label="Keep existing files instead of overwriting them")
            dialog.get_content_area().pack_start(keep_existing_check, False, False, 4)
            keep_existing_check.show()
            response = dialog.run()
            choice = dialog.choice if response == Gtk.ResponseType.OK else None
            keep_existing = keep_existing_check.get_active()
            dialog.destroy()
            if choice is None:
                return
        else:
            confirm = Gtk.MessageDialog(
                transient_for=self, modal=True,
                message_type=Gtk.MessageType.QUESTION,
                text=f"Install {pkg['name']} {pkg['version']}?",
            )
            confirm.format_secondary_text(
                "This is a real Debian package, fetched and installed best-effort "
                "-- LinuxDoors is its own from-scratch build with a different "
                "glibc/library baseline than Debian, not a Debian derivative, so "
                "this isn't guaranteed to work for every package. Maintainer "
                "scripts are never run."
            )
            keep_existing_check = Gtk.CheckButton(
                label="Keep existing files instead of overwriting them")
            confirm.get_message_area().pack_start(keep_existing_check, False, False, 4)
            keep_existing_check.show()
            confirm.add_buttons(
                "Cancel", Gtk.ResponseType.CANCEL,
                "Install", Gtk.ResponseType.OK,
            )
            ok_btn = confirm.get_widget_for_response(Gtk.ResponseType.OK)
            ok_btn.get_style_context().add_class("suggested-action")
            response = confirm.run()
            keep_existing = keep_existing_check.get_active()
            confirm.destroy()
            if response != Gtk.ResponseType.OK:
                return
            choice = "precompiled"

        if choice == "source":
            fn = lambda progress: deb_backend.install_from_source(
                pkg["name"], progress=progress, overwrite_existing=not keep_existing)
        else:
            fn = lambda progress: deb_backend.install(
                pkg["name"], progress, overwrite_existing=not keep_existing)
        self._run_with_progress(f"Installing {pkg['name']}", fn)

    def _confirm_upgrade(self, pkg, manifest):
        dialog = Gtk.MessageDialog(
            transient_for=self, modal=True,
            message_type=Gtk.MessageType.QUESTION,
            text=f"Upgrade {pkg['name']}?",
        )
        dialog.format_secondary_text(
            f"The installed copy is at {manifest.get('version', 'unknown')} -- "
            f"{pkg['version']} is available. Upgrading applies the newer "
            "version's files over the current install (a precompiled "
            "download or a local source build, your choice)."
        )
        dialog.add_buttons(
            "Cancel", Gtk.ResponseType.CANCEL,
            "Upgrade", Gtk.ResponseType.OK,
        )
        ok_btn = dialog.get_widget_for_response(Gtk.ResponseType.OK)
        ok_btn.get_style_context().add_class("suggested-action")
        response = dialog.run()
        dialog.destroy()
        if response == Gtk.ResponseType.OK:
            self._start_install(pkg)

    def _show_base_package_notice(self, pkg):
        dialog = Gtk.MessageDialog(
            transient_for=self, modal=True,
            message_type=Gtk.MessageType.INFO,
            text=f"{pkg['name']} is part of the base system",
        )
        dialog.format_secondary_text(
            "This package shipped as part of the LinuxDoors base image, "
            "so it can't be uninstalled from here -- only packages you "
            "install yourself through this app can be removed this way."
        )
        dialog.add_button("OK", Gtk.ResponseType.OK)
        dialog.run()
        dialog.destroy()

    def _confirm_uninstall(self, pkg):
        dialog = Gtk.MessageDialog(
            transient_for=self, modal=True,
            message_type=Gtk.MessageType.QUESTION,
            text=f"Uninstall {pkg['name']}?",
        )
        dialog.format_secondary_text(
            "This removes every file that was installed for this package."
        )
        dialog.add_buttons(
            "Cancel", Gtk.ResponseType.CANCEL,
            "Uninstall", Gtk.ResponseType.OK,
        )
        ok_btn = dialog.get_widget_for_response(Gtk.ResponseType.OK)
        ok_btn.get_style_context().add_class("destructive-action")
        response = dialog.run()
        dialog.destroy()
        if response == Gtk.ResponseType.OK:
            self._run_with_progress(
                f"Uninstalling {pkg['name']}",
                lambda progress: backend.uninstall(pkg["name"], progress),
            )

    def _start_install(self, pkg):
        if not pkg.get("download_url"):
            self._show_error(f"{pkg['name']} has no precompiled download yet -- "
                              "only 'Build from source' is available.")
            choice = "source"
        else:
            dialog = ChoiceDialog(self, pkg["name"])
            response = dialog.run()
            choice = dialog.choice if response == Gtk.ResponseType.OK else None
            dialog.destroy()
            if choice is None:
                return

        if choice == "precompiled":
            fn = lambda progress: backend.install_precompiled(
                pkg["name"], pkg["version"], pkg["download_url"], progress)
        else:
            fn = lambda progress: backend.install_from_source(
                pkg["name"], pkg["version"], progress)

        self._run_with_progress(f"Installing {pkg['name']}", fn)

    def _run_with_progress(self, title, work_fn):
        progress_dialog = ProgressDialog(self, title)

        def worker():
            try:
                work_fn(progress_dialog.set_status)
                GLib.idle_add(self._finish, progress_dialog, None)
            except Exception as exc:
                GLib.idle_add(self._finish, progress_dialog, str(exc))

        threading.Thread(target=worker, daemon=True).start()

    def _finish(self, progress_dialog, error):
        progress_dialog.destroy()
        if error:
            self._show_error(error)
        self._refresh_thread()

    def _show_error(self, message):
        dialog = Gtk.MessageDialog(
            transient_for=self, modal=True,
            message_type=Gtk.MessageType.ERROR,
            text="Something went wrong",
        )
        dialog.format_secondary_text(message)
        dialog.add_button("OK", Gtk.ResponseType.OK)
        dialog.run()
        dialog.destroy()


def cli_install(args):
    """Plain-text install, no GTK -- this is what the linuxdoors-pkg-watch
    background watcher actually spawns (inside an xfce4-terminal running
    'su -c ... root', matching the same elevation pattern the Desktop
    launcher already uses), after the user picks precompiled-vs-source
    from the watcher's own notification dialog.
    """
    if len(args) < 3:
        print("usage: linuxdoors-pkg-manager --cli-install <name> <version> <method> [zip_path]",
              file=sys.stderr)
        sys.exit(2)
    name, version, method = args[0], args[1], args[2]

    def progress(msg):
        print(f"  {msg}", flush=True)

    print(f"Installing {name} {version} ({method})...")
    try:
        if method == "precompiled-download":
            zip_path = args[3]
            backend.install_from_downloaded_zip(name, version, zip_path, progress)
        elif method == "source":
            backend.install_from_source(name, version, progress)
        else:
            print(f"unknown method {method!r}", file=sys.stderr)
            sys.exit(2)
    except Exception as exc:
        print(f"FAILED: {exc}", file=sys.stderr)
        input("Press Enter to close...")
        sys.exit(1)
    print(f"{name} installed successfully.")
    input("Press Enter to close...")


def main():
    if os.geteuid() != 0:
        print("linuxdoors-pkg-manager must run as root.", file=sys.stderr)
        sys.exit(1)
    if len(sys.argv) > 1 and sys.argv[1] == "--cli-install":
        cli_install(sys.argv[2:])
        return
    win = MainWindow()
    win.connect("destroy", Gtk.main_quit)
    win.show_all()
    Gtk.main()


if __name__ == "__main__":
    main()
