#!/usr/bin/env python3
"""Starchaser Linux's one command: starchaser AREA [VERB] [ARG ...] runs a Starchaser tool."""
# Discovery and longest-route dispatch are inspired by Omarchy (MIT),
# https://github.com/basecamp/omarchy/blob/748fa3c0d/bin/omarchy. No code copied.
#
# The tools themselves live off PATH: beside this file (a checkout's bin/, or /usr/share/starchaser/bin that
# /usr/bin/starchaser links to), then /usr/lib/starchaser/bin (the package's links). STARCHASER_TOOLS, a
# colon-separated list of folders, replaces that search; tests use it to stand in for tools.
import json
import os
from pathlib import Path
import re
import sys

BIN = Path(__file__).resolve().parent
LIBEXEC = Path("/usr/lib/starchaser/bin")
INSTALLED = Path("/usr/share/starchaser/bin")
WORD = re.compile(r"[a-z0-9][a-z0-9-]*")
EVERYDAY = ("software", "updates", "recovery", "settings", "lock", "screenshot", "fleet", "mission-control",
            "ai-account", "link")


def folders():
    if os.environ.get("STARCHASER_TOOLS"):
        return [Path(p) for p in os.environ["STARCHASER_TOOLS"].split(":") if p]
    if BIN == INSTALLED:   # the package's copy: by its links, the path the system helpers know the tools by
        return [LIBEXEC, BIN]
    return [BIN, LIBEXEC]   # a checkout's own tools first; the package's extras (the screensaver) after


def find(name):
    for folder in folders():
        path = folder / name
        if path.is_file() and os.access(path, os.X_OK):
            return path
    return None


def route(args):
    """(tool path, its arguments) for the longest run of leading words that names a tool, else (None, args)."""
    words = []
    for arg in args[:6]:
        if not WORD.fullmatch(arg):
            break
        words.append(arg)
    for count in range(len(words), 0, -1):
        path = find("starchaser-" + "-".join(words[:count]))
        if path:
            return path, args[count:]
    if words[:1] == ["ai"]:   # 'starchaser ai' is 'starchaser ai account'
        path = find("starchaser-" + "ai-account")
        if path:
            return path, args[1:]
    return None, args


def commands():
    rows, seen = [], set()
    for folder in folders():
        for path in sorted(folder.glob("starchaser-*")):
            if path.name in seen or not path.is_file() or not os.access(path, os.X_OK):
                continue
            seen.add(path.name)
            try:
                text = path.read_text()
            except (OSError, UnicodeDecodeError):
                text = ""   # a compiled program (the screensaver): it runs, but has no summary to list
            summaries = [line.removeprefix("# summary:").strip() for line in text.splitlines()
                         if line.startswith("# summary:")]
            if (len(summaries) != 1 or not summaries[0]) and path.resolve().parent != BIN:
                continue
            if len(summaries) != 1 or not summaries[0]:
                raise ValueError(f"{path.name} needs exactly one '# summary:' line")
            rows.append({"command": "starchaser " + path.name.removeprefix("starchaser-").replace("-", " "),
                         "binary": path.name, "summary": summaries[0]})
    return sorted(rows, key=lambda row: row["command"])


def listing(rows):
    for row in rows:
        print(f"  {row['command'][11:]:<23} {row['summary']}")


def main_help():
    rows = commands()
    print("Usage: starchaser AREA [VERB] [ARG ...]\n       starchaser AREA --help\n       starchaser commands [--json]\n")
    print("Everyday commands (multiword names also accept hyphens):")
    by_binary = {row["binary"]: row for row in rows}
    listing([by_binary["starchaser-" + name] for name in EVERYDAY if "starchaser-" + name in by_binary])
    print("\nA command on its own does what it says: 'starchaser lock' locks the screen and 'starchaser settings'"
          "\nopens Settings. Add --help to any command for its options. 'starchaser ai' is short for 'starchaser ai account'.")
    print("\nExamples:\n  starchaser updates check\n  starchaser recovery list\n  starchaser settings updates"
          "\n  starchaser software search video player\n  starchaser fleet doctor\n  starchaser ai list"
          "\n  starchaser link pair 192.168.1.20")
    print("\nRun 'starchaser commands' for every tool.")
    return 0


def run(path, args):
    os.execv(str(path), [path.name, *args])


def main(args):
    if not args or args in (["--help"], ["-h"], ["help"]):
        return main_help()
    if args[0] == "commands":
        if args[1:] in (["--help"], ["-h"], ["help"]):
            print("Usage: starchaser commands [--json]\n\nList every command and its summary. --json prints an array of "
                  "command, binary, and summary objects.")
            return 0
        if args[1:] not in ([], ["--json"]):
            print("starchaser: commands takes only --json. Run 'starchaser commands --help' for more help.", file=sys.stderr)
            return 2
        rows = commands()
        if args[1:]:
            print(json.dumps(rows, ensure_ascii=True, indent=2))
        else:
            listing(rows)
        return 0
    path, rest = route(args)
    if path:
        return run(path, rest)
    words = [a for a in args if WORD.fullmatch(a)]
    prefix = "starchaser " + " ".join(words)
    children = [r for r in commands() if r["command"].startswith(prefix + " ")] if words else []
    if children:
        print(f"Usage: {prefix} COMMAND [ARG ...]\n")
        listing(children)
        return 0
    print(f"starchaser: unknown command {args[0]!r}. Run 'starchaser --help' for more help.", file=sys.stderr)
    return 2


if __name__ == "__main__":
    try:
        sys.exit(main(sys.argv[1:]))
    except (OSError, ValueError) as exc:
        print(f"starchaser: {exc}", file=sys.stderr)
        sys.exit(1)
