"""About — Überblick über System und Hardware (read-only)."""
from __future__ import annotations

import gi

gi.require_version("Adw", "1")
from gi.repository import Adw, Gtk  # noqa: E402

from taninux.core import sysinfo


def _ver() -> str:
    try:
        from importlib.metadata import version
        return version("taninux")
    except Exception:  # noqa: BLE001
        return "0.2.0"


def _row(title: str, value: str) -> Adw.ActionRow:
    row = Adw.ActionRow(title=title)
    lbl = Gtk.Label(label=value, xalign=1.0, wrap=True)
    lbl.add_css_class("dim-label")
    lbl.set_selectable(True)
    row.add_suffix(lbl)
    return row


def _fmt_gib(b: int) -> str:
    return f"{b / 1024**3:.1f} GiB" if b else "—"


def _uptime(sec: float) -> str:
    m = int(sec // 60)
    d, h, m = m // 1440, (m % 1440) // 60, m % 60
    if d:
        return f"{d}d {h}h {m}m"
    return f"{h}h {m}m" if h else f"{m}m"


def build() -> Gtk.Widget:
    page = Adw.PreferencesPage()
    mem = sysinfo.memory()
    gpus = sysinfo.gpus()

    g_sys = Adw.PreferencesGroup(title="System")
    g_sys.add(_row("Device", sysinfo.hostname()))
    g_sys.add(_row("Operating system", sysinfo.distro_pretty()))
    g_sys.add(_row("Kernel", sysinfo.kernel_release()))
    g_sys.add(_row("TANINUX", _ver()))
    page.add(g_sys)

    g_hw = Adw.PreferencesGroup(title="Hardware")
    g_hw.add(_row("Processor", f"{sysinfo.cpu_model()}  ·  {sysinfo.cpu_count()} cores"))
    g_hw.add(_row("Memory", _fmt_gib(mem.get("MemTotal", 0))))
    if gpus:
        for i, gpu in enumerate(gpus):
            title = "Graphics" if i == 0 else ""
            g_hw.add(_row(title, gpu.model))
    page.add(g_hw)

    g_st = Adw.PreferencesGroup(title="Status")
    g_st.add(_row("Uptime", _uptime(sysinfo.uptime_seconds())))
    page.add(g_st)

    return page
