#!/usr/bin/env python3
# FWS — « About » window: two tabs, « The FWS project » (what FWS is, version,
# links) and « System » (detected hardware and software). Replaces the « About
# Xfce » of libxfce4ui with an FWS-branded page. Texts come from
# system-translations.toml (about.* keys). GTK3 (python-gobject installed with
# the desktop).

import os
import re
import subprocess
import sys

import gi

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

sys.path.insert(0, "/usr/local/lib/fws")
from fws_i18n import catalog  # noqa: E402

t = catalog("system").t

GLib.set_prgname("fws-about")


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


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


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


def _mem():
    try:
        with open("/proc/meminfo") as fh:
            for line in fh:
                if line.startswith("MemTotal"):
                    kib = int(line.split()[1])
                    return t("about.memory_size", size=f"{kib / 1048576:.1f}")
    except OSError:
        pass
    return t("about.unknown")


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


def _desktop():
    if os.environ.get("HYPRLAND_INSTANCE_SIGNATURE"):
        return "Hyprland"
    env = os.environ.get("XDG_CURRENT_DESKTOP") \
        or os.environ.get("DESKTOP_SESSION") or ""
    return env or t("about.unknown")


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


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


def _grid(rows):
    grid = Gtk.Grid(column_spacing=18, row_spacing=8, margin=18)
    for i, (key, val) in enumerate(rows):
        k = Gtk.Label(xalign=1)
        k.set_markup(f"<b>{GLib.markup_escape_text(key)}</b>")
        k.get_style_context().add_class("dim-label")
        v = Gtk.Label(label=val, xalign=0, selectable=True)
        v.set_line_wrap(True)
        grid.attach(k, 0, i, 1, 1)
        grid.attach(v, 1, i, 1, 1)
    return grid


def _project_tab(osr):
    box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10, margin=20)
    title = Gtk.Label()
    name = osr.get("PRETTY_NAME") or osr.get("NAME") or "FWS Linux"
    title.set_markup(f"<span size='xx-large' weight='bold'>{name}</span>")
    box.pack_start(title, False, False, 0)

    tag = Gtk.Label(label=t("about.tagline"))
    tag.set_line_wrap(True)
    tag.set_max_width_chars(52)
    box.pack_start(tag, False, False, 0)

    feats = Gtk.Label()
    feats.set_markup(t("about.features"))
    feats.set_line_wrap(True)
    feats.set_max_width_chars(52)
    feats.set_xalign(0)
    box.pack_start(feats, False, False, 6)

    home = osr.get("HOME_URL") or "https://gitea.nocode-var.tech/FWS/FWS-ISO"
    link = Gtk.LinkButton.new_with_label(home, t("about.project_website"))
    box.pack_start(link, False, False, 0)
    return box


def _system_tab(osr):
    rows = [
        (t("about.system_label"), osr.get("PRETTY_NAME", "FWS Linux")),
        (t("about.build_label"), osr.get("BUILD_ID", "rolling")),
        (t("about.kernel_label"), _cmd("uname", "-r") or t("about.unknown")),
        (t("about.desktop_label"), _desktop()),
        (t("about.display_label"), _session_type()),
        (t("about.hostname_label"), _cmd("hostname") or os.uname().nodename),
        (t("about.processor_label"), _cpu()),
        (t("about.memory_label"), _mem()),
        (t("about.graphics_label"), "\n".join(_gpus())),
        (t("about.disks_label"), "\n".join(_disks())),
    ]
    scroll = Gtk.ScrolledWindow()
    scroll.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
    scroll.add(_grid(rows))
    return scroll


class AboutWindow(Gtk.Window):
    def __init__(self):
        super().__init__(title=t("about.window_title"))
        self.set_default_size(520, 460)
        self.set_position(Gtk.WindowPosition.CENTER)
        self.set_type_hint(Gdk.WindowTypeHint.DIALOG)

        osr = _osrelease()
        notebook = Gtk.Notebook()
        notebook.append_page(_project_tab(osr),
                             Gtk.Label(label=t("about.project_tab")))
        notebook.append_page(_system_tab(osr),
                             Gtk.Label(label=t("about.system_tab")))
        self.add(notebook)
        self.connect("destroy", Gtk.main_quit)


def main():
    if not Gtk.init_check()[0]:
        return 1
    win = AboutWindow()
    win.show_all()
    Gtk.main()
    return 0


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