#!/usr/bin/env python3
# pkgsearch - search installed packages by name or description
# Usage: pkgsearch QUERY [--regex] [--description] [--limit N]
import argparse, os, re, shutil, subprocess, sys

def installed():
    pkgs = []
    if shutil.which("dpkg-query"):
        r = subprocess.run(["dpkg-query", "-W", "-f=${Package}\t${Version}\t${Description}\n"],
                           capture_output=True, text=True)
        for line in r.stdout.splitlines():
            parts = line.split("\t")
            if len(parts) >= 2:
                pkgs.append((parts[0], parts[1], parts[2] if len(parts) > 2 else ""))
        return pkgs, "dpkg"
    if shutil.which("pacman"):
        r = subprocess.run(["pacman", "-Q"], capture_output=True, text=True)
        for line in r.stdout.splitlines():
            parts = line.split()
            if len(parts) >= 2:
                pkgs.append((parts[0], parts[1], ""))
        return pkgs, "pacman"
    return pkgs, None

def selftest():
    out = subprocess.run([sys.executable, os.path.abspath(__file__), "bash"],
                         capture_output=True, text=True)
    assert out.returncode == 0, out.stderr
    assert "bash" in out.stdout.lower(), out.stdout
    out = subprocess.run([sys.executable, os.path.abspath(__file__), "zzzz-no-such-pkg-zzz"],
                         capture_output=True, text=True)
    assert out.returncode == 0 and "no installed package matches" in out.stdout.lower()
    print("pkgsearch selftest: PASS")
    return 0

def main():
    ap = argparse.ArgumentParser(prog="pkgsearch",
        description="Search installed packages by name or description.")
    ap.add_argument("query", nargs="?", help="search term (substring, or regex with --regex)")
    ap.add_argument("--regex", action="store_true", help="treat QUERY as a regular expression")
    ap.add_argument("--description", action="store_true",
                    help="also match the package description (default: name only)")
    ap.add_argument("--limit", type=int, default=30, help="max results (default 30)")
    ap.add_argument("--selftest", action="store_true", help="run built-in self-test and exit")
    a = ap.parse_args()
    if a.selftest:
        return selftest()
    if not a.query:
        ap.error("a search term is required")
    pkgs, backend = installed()
    if backend is None:
        print("pkgsearch: no supported package manager found.", file=sys.stderr); return 1
    if a.regex:
        try:
            pat = re.compile(a.query, re.IGNORECASE)
        except re.error as e:
            print("pkgsearch: bad regex: %s" % e, file=sys.stderr); return 2
        match = lambda s: bool(pat.search(s))
    else:
        q = a.query.lower()
        match = lambda s: q in s.lower()
    hits = []
    for name, ver, desc in pkgs:
        if match(name) or (a.description and match(desc)):
            hits.append((name, ver, desc))
    if not hits:
        print("pkgsearch: no installed package matches %r." % a.query); return 0
    print("pkgsearch: %d match(es) for %r (installed, %s):" % (len(hits), a.query, backend))
    for name, ver, desc in hits[:a.limit]:
        line = "  %-35s %s" % (name, ver)
        if a.description and desc:
            line += "  %s" % desc[:80]
        print(line)
    if len(hits) > a.limit:
        print("  ... and %d more" % (len(hits) - a.limit))
    return 0

if __name__ == "__main__":
    sys.exit(main())
