#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""LinuxDoors pkg CLI -- Termux-shaped. 'update'/'upgrade'/'install' are
implemented; 'remove'/'hold' are deliberately out of scope here (see
CLAUDE.md's "Package update/versioning system" plan). Imports
linuxdoors_pkg_backend directly rather than duplicating any install/version
logic -- same module the GUI and the pkg-watch CLI path already share, which
is also why 'pkg install' automatically pulls in a package's own missing
runtime dependencies (e.g. `pkg install qtwebengine` installs qt6-full
first if it isn't already on the system) -- that behavior lives once, in
backend._ensure_deps_installed(), and every install entry point (this CLI,
the GUI's double-click install, and the browser-download watcher) shares it.
"""
import os
import sys

sys.path.insert(0, "/usr/local/lib/linuxdoors-pkg")
import linuxdoors_pkg_backend as backend

USAGE = "usage: pkg update | pkg upgrade [--source] | pkg install <name> [<name> ...] [--source]"


def cmd_update():
    items = backend.list_upgradable()
    if not items:
        print("0 packages to update")
        return
    print(f"{len(items)} package(s) can be upgraded:")
    for it in items:
        print(f"  {it['name']}: {it['installed_version']} -> {it['available_version']}")


def cmd_upgrade(force_source):
    items = backend.list_upgradable()
    if not items:
        print("0 packages to upgrade")
        return
    print(f"Upgrading {len(items)} package(s)"
          + (" from source..." if force_source else " (precompiled where available)..."))
    result = backend.upgrade_all(
        progress=lambda msg: print(f"  {msg}"), force_source=force_source,
    )
    for u in result["upgraded"]:
        note = ""
        if u["fallback"]:
            note = " (no precompiled build available yet, built from source)"
        elif u["method"] == "source":
            note = " (source)"
        print(f"  {u['name']}: {u['from_version']} -> {u['to_version']}{note}")
    for f in result["failed"]:
        print(f"  {f['name']}: FAILED -- {f['error']}", file=sys.stderr)
    print(f"Upgraded {len(result['upgraded'])}/{result['total']} package(s)"
          + (f", {len(result['failed'])} failed" if result["failed"] else "") + ".")


def install_one(name, pkg, force_source):
    """Install one catalog entry; True on success."""
    use_source = force_source or not pkg.get("download_url")
    print(f"Installing {name} {pkg['version']}"
          + (" from source..." if use_source else " (precompiled)..."))
    try:
        if use_source:
            backend.install_from_source(name, pkg["version"], lambda msg: print(f"  {msg}"))
        else:
            backend.install_precompiled(
                name, pkg["version"], pkg["download_url"], lambda msg: print(f"  {msg}")
            )
    except Exception as exc:
        print(f"FAILED: {name}: {exc}", file=sys.stderr)
        return False
    print(f"{name} installed successfully.")
    return True


def cmd_install(names, force_source):
    """pkg install <name> [<name> ...] -- every name is checked against the
    catalog first (an unknown name installs nothing); then each is installed
    in the order given. One that is already installed -- or was just pulled in
    as a dependency of an earlier one -- is skipped; a failure does not stop
    the rest, but makes pkg exit with an error."""
    names = list(dict.fromkeys(names))      # drop repeats, keep the order
    if not names:
        print(USAGE, file=sys.stderr)
        sys.exit(2)
    try:
        packages = {p["name"]: p for p in backend.list_packages()}
    except Exception as exc:
        print(f"could not reach the package catalog: {exc}", file=sys.stderr)
        sys.exit(1)
    unknown = [n for n in names if n not in packages]
    if unknown:
        print("no such package: " + ", ".join(unknown), file=sys.stderr)
        print("nothing was installed.", file=sys.stderr)
        sys.exit(1)

    done, skipped, failed = [], [], []
    for name in names:
        if backend.is_installed(name):
            print(f"{name} is already installed.")
            skipped.append(name)
            continue
        (done if install_one(name, packages[name], force_source) else failed).append(name)

    if len(names) > 1:
        parts = [f"{len(done)} installed"]
        if skipped:
            parts.append(f"{len(skipped)} already installed")
        if failed:
            parts.append(f"{len(failed)} failed ({', '.join(failed)})")
        print(", ".join(parts) + ".")
    if failed:
        sys.exit(1)


def main():
    args = sys.argv[1:]
    if not args:
        print(USAGE, file=sys.stderr)
        sys.exit(2)
    if os.geteuid() != 0:
        print("pkg must be run as root", file=sys.stderr)
        sys.exit(1)
    cmd, rest = args[0], args[1:]
    if cmd == "update":
        cmd_update()
    elif cmd == "upgrade":
        cmd_upgrade(force_source="--source" in rest)
    elif cmd == "install":
        cmd_install([a for a in rest if not a.startswith("--")],
                    force_source="--source" in rest)
    else:
        print(USAGE, file=sys.stderr)
        sys.exit(2)


if __name__ == "__main__":
    main()
