#!/usr/bin/env python3
# summary: Show this computer's version and system information.
"""starchaser about: what this computer is and runs, as JSON (Settings > About), or as text (`--text`)."""
import json
import os
import re
import shutil
import subprocess
import sys
from pathlib import Path


def rd(p: str) -> str:
    try:
        return Path(p).read_text().strip()
    except OSError:
        return ""


def out(*cmd) -> str:
    if not shutil.which(cmd[0]):
        return ""
    try:
        return subprocess.run(cmd, capture_output=True, text=True, timeout=5).stdout.strip()
    except (OSError, subprocess.TimeoutExpired):
        return ""


def kernel_name(release: str) -> str:
    """Starchaser's own kernels by their whole name ("7.2.14-Starchaser", "6.18.59-Starchaser-LTS", and the
    "7.2.14-starchaser3" form of kernels built before 2026-11-16); any other kernel by its version number alone."""
    if re.fullmatch(r"[0-9][0-9A-Za-z.+_-]*-(?:Starchaser(?:-LTS)?|starchaser(?:-lts)?[0-9]+)", release):
        return release
    match = re.match(r"[0-9]+(?:\.[0-9]+)*", release)
    return match.group(0) if match else release


def os_release() -> dict:
    d = {}
    for line in rd("/etc/os-release").splitlines():
        k, _, v = line.partition("=")
        d[k] = v.strip('"')
    return d


# what the starchaser-desktop package installed ("<pkgver>-<pkgrel>"): a package install has no git checkout
PACKAGE_VERSION = Path("/usr/share/starchaser/VERSION")


# the checkout this script lives in, when it runs from one (a developer's machine links its tools there)
SELF_REPO = Path(__file__).resolve().parent.parent


def checkout():
    """The Starchaser git checkout on this machine, or None on a package install."""
    return next((r for r in (Path.home() / ".local/share/starchaser/repo", Path.home() / "starchaser", SELF_REPO)
                 if (r / ".git").exists()), None)


def build() -> str:
    # the Starchaser checkout: an installed machine's, a developer's ~/starchaser, or the one this script runs from
    repo = checkout()
    if repo is None:
        return rd(str(PACKAGE_VERSION))
    return out("git", "-C", str(repo), "log", "-1", "--format=%h, %ad", "--date=format:%b %-d, %Y")


RELEASE = "0.3"     # bump with each public release


def version() -> str:
    """The number people read: "Starchaser Linux 0.3 (October 2026)". The build code stays separate, below it."""
    # only a tagged release ("0.3.0-1") names the public number; a build ("0.4321.gabc1234-1") counts commits
    m = re.match(r"(\d+\.\d+)(?:\.\d+)?-\d+\s*$", rd(str(PACKAGE_VERSION)).strip())
    num = m.group(1) if m else RELEASE
    when = ""
    repo = checkout()
    if repo is not None:
        when = out("git", "-C", str(repo), "log", "-1", "--format=%ad", "--date=format:%B %Y")
    elif PACKAGE_VERSION.exists():
        import time
        when = time.strftime("%B %Y", time.localtime(PACKAGE_VERSION.stat().st_mtime))
    return f"{num} ({when})" if when else num


def cpu() -> str:
    name = next((l.split(":", 1)[1].strip() for l in rd("/proc/cpuinfo").splitlines() if l.startswith("model name")), "")
    name = re.sub(r"\s+(w/|with) .*$", "", name)                       # "... w/ Radeon 780M Graphics"
    name = re.sub(r"\((R|TM)\)|\s+CPU|\s+\d+-Core Processor", "", name).strip()
    return f"{name} ({os.cpu_count()} threads)" if name else ""


def gpus() -> list:
    # AMD processors name their built-in graphics ("... w/ Radeon 780M Graphics"); lspci only has the codename
    igpu = re.search(r"(?:w/|with) (Radeon [\w ]+?) Graphics", next((l for l in rd("/proc/cpuinfo").splitlines() if l.startswith("model name")), ""))
    names = []
    for line in out("lspci", "-mm").splitlines():
        f = re.findall(r'"([^"]*)"', line)
        if len(f) >= 3 and re.search(r"VGA|3D|Display", f[0]):
            vendor, dev = f[1], f[2]
            m = re.search(r"\[([^\]]+)\]", dev)                         # "AD103 [GeForce RTX 4080]"
            short = m.group(1) if m else dev
            v = "NVIDIA" if "NVIDIA" in vendor else "AMD" if re.search(r"AMD|ATI", vendor) else "Intel" if "Intel" in vendor else vendor
            if v == "AMD" and igpu and not re.search(r"Radeon (RX|Pro)", short):
                short = igpu.group(1)
            names.append(f"{v} {short}".replace("Radeon Radeon", "Radeon"))
    return names


def memory() -> str:
    """Installed memory: the kernel's total is short by what firmware/graphics reserve (32 GB shows as 29),
    so round up to the next standard size, but only when it's close (within 15%): 1 GB showed as 2 GB when the
    sizes started at 2, and an odd size such as a 5 GB virtual machine is shown as it is."""
    kb = next((int(l.split()[1]) for l in rd("/proc/meminfo").splitlines() if l.startswith("MemTotal")), 0)
    if not kb:
        return ""
    gb = kb / 1024 / 1024
    sizes = [1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024]
    up = next((x for x in sizes if x >= gb * 0.99), None)
    return f"{up if up and gb >= up * 0.85 else max(1, round(gb))} GB"


def disk() -> str:
    try:
        st = shutil.disk_usage("/")
    except OSError:
        return ""
    gb = lambda b: f"{b / 1e12:.1f} TB" if b >= 1e12 else f"{round(b / 1e9)} GB"
    return f"{gb(st.used)} used of {gb(st.total)}"


def uptime() -> str:
    try:
        s = int(float(rd("/proc/uptime").split()[0]))
    except (ValueError, IndexError):
        return ""
    d, h, m = s // 86400, s % 86400 // 3600, s % 3600 // 60
    parts = ([f"{d} day" + ("s" if d != 1 else "")] if d else []) + ([f"{h} hour" + ("s" if h != 1 else "")] if h else [])
    return ", ".join(parts) or f"{m} minute" + ("s" if m != 1 else "")


def info() -> dict:
    osr = os_release()
    vendors = {"Micro Computer (HK) Tech Limited": "Minisforum", "Micro-Star International Co., Ltd.": "MSI",
               "ASUSTeK COMPUTER INC.": "ASUS", "LENOVO": "Lenovo", "Dell Inc.": "Dell", "HP": "HP"}
    vendor = rd("/sys/class/dmi/id/sys_vendor")
    model = " ".join(x for x in (vendors.get(vendor, vendor), rd("/sys/class/dmi/id/product_name"))
                     if x and "To Be Filled" not in x and "System Product" not in x)
    if not model or model.startswith("MSI MS-") or len(model) < 6:              # desktops: name the board instead
        board = rd("/sys/class/dmi/id/board_name")
        if board:
            model = (rd("/sys/class/dmi/id/board_vendor").replace("Micro-Star International Co., Ltd.", "MSI") + " " + board).strip()
    hypr = out("hyprctl", "version", "-j")
    try:
        hypr = json.loads(hypr).get("tag", "") or ""
    except ValueError:
        hypr = ""
    m = re.search(r"\d+\.\d+(\.\d+)?", out("qs", "--version"))
    qs = m.group(0) if m else ""
    # os-release names Starchaser itself, so the base comes from ID_LIKE (the distribution it builds on). Kept in the
    # JSON only: About and Copy system info show no other distribution's name (owner's call, for now)
    base = {"arch": "Arch Linux"}.get((osr.get("ID_LIKE", "").split() or [""])[0], "")
    if not base and osr.get("ID") not in ("", "starchaser"):    # a machine that isn't Starchaser underneath
        base = osr.get("PRETTY_NAME", osr.get("NAME", ""))
    return {
        "name": "Starchaser Linux",
        "version": version(),
        "build": build(),
        "base": base,
        "hostname": rd("/etc/hostname") or os.uname().nodename,
        "model": model,
        "cpu": cpu(),
        "gpus": gpus(),
        "memory": memory(),
        "disk": disk(),
        "kernel": kernel_name(os.uname().release),
        "desktop": "Starchaser Desktop",
        "hyprland": hypr.lstrip("v"),
        "quickshell": qs,
        "uptime": uptime(),
    }


USAGE = """Usage: starchaser about [--text]

Shows this computer's details (system, model, processor, graphics, memory, storage), as JSON;
--text prints them as plain lines instead (what Settings > About copies)."""

if __name__ == "__main__":
    if sys.argv[1:] == ["help"] or any(a in ("-h", "--help") for a in sys.argv[1:]):
        print(USAGE)
        sys.exit(0)
    if any(a != "--text" for a in sys.argv[1:]):
        bad = next(a for a in sys.argv[1:] if a != '--text')
        # a bare word isn't an option: say what it is ("status" was called "unknown option status")
        why = f"unknown option '{bad}'" if bad.startswith("-") else f"there is no command '{bad}'; it only takes --text"
        print(f"starchaser about: {why}\nRun 'starchaser about --help' for more help.\n\n{USAGE}", file=sys.stderr)
        sys.exit(2)
    i = info()
    if "--text" in sys.argv:
        rows = [("System", " ".join(x for x in (i["name"], i["version"]) if x) + (f", build {i['build']}" if i["build"] else "")),
                ("Computer", i["hostname"]), ("Model", i["model"]), ("Processor", i["cpu"]),
                ("Graphics", ", ".join(i["gpus"])), ("Memory", i["memory"]), ("Storage", i["disk"]),
                ("Kernel", i["kernel"]), ("Desktop", i["desktop"]), ("Up for", i["uptime"])]
        print("\n".join(f"{k + ':':11} {v}" for k, v in rows if v))
    else:
        print(json.dumps(i))
