#!/usr/bin/env python3
# aliaslist - list shell aliases and functions with their definitions
# Usage: aliaslist [--file FILE]... [--shell bash|zsh] [--functions] [--aliases]
import argparse, os, re, subprocess, sys

RC_FILES = {
    "bash": ["~/.bashrc", "~/.bash_aliases", "~/.bash_profile"],
    "zsh": ["~/.zshrc", "~/.zsh_aliases"],
    "sh": ["~/.profile"],
}

def parse_rc(path):
    aliases, funcs = {}, {}
    try:
        text = open(path, errors="replace").read()
    except OSError:
        return aliases, funcs
    for m in re.finditer(r"(?m)^\s*alias\s+([A-Za-z0-9_][\w.-]*)\s*=\s*(.+?)\s*$", text):
        aliases[m.group(1)] = m.group(2).strip().strip("'\"")
    for m in re.finditer(r"(?m)^\s*(?:function\s+)?([A-Za-z_][\w]*)\s*\(\s*\)\s*\{", text):
        funcs[m.group(1)] = "defined in %s" % path
    return aliases, funcs

def live_aliases(shell):
    r = subprocess.run([shell, "-ic", "alias"], capture_output=True, text=True, timeout=15)
    out = {}
    for line in r.stdout.splitlines():
        m = re.match(r"alias\s+([\w.-]+)='(.*)'\s*$", line.strip())
        if m:
            out[m.group(1)] = m.group(2)
    return out

def selftest():
    import tempfile
    with tempfile.TemporaryDirectory() as d:
        rc = os.path.join(d, ".bashrc")
        open(rc, "w").write("alias ll='ls -la'\nalias gs='git status'\nmyfunc() { echo hi; }\n")
        out = subprocess.run([sys.executable, os.path.abspath(__file__), "--file", rc],
                             capture_output=True, text=True)
        assert out.returncode == 0, out.stderr
        assert "ll" in out.stdout and "ls -la" in out.stdout, out.stdout
        assert "myfunc" in out.stdout
        print("aliaslist selftest: PASS")
    return 0

def main():
    ap = argparse.ArgumentParser(prog="aliaslist",
        description="List shell aliases and functions with their definitions.")
    ap.add_argument("--file", action="append", default=[], help="rc file to parse (repeatable)")
    ap.add_argument("--shell", default="bash", choices=["bash", "zsh", "sh"],
                    help="shell whose rc files to read (default bash)")
    ap.add_argument("--live", action="store_true", help="also query the live interactive shell for aliases")
    ap.add_argument("--aliases", action="store_true", help="show aliases only")
    ap.add_argument("--functions", action="store_true", help="show functions only")
    ap.add_argument("--selftest", action="store_true", help="run built-in self-test and exit")
    a = ap.parse_args()
    if a.selftest:
        return selftest()
    files = a.file or [os.path.expanduser(p) for p in RC_FILES[a.shell]]
    aliases, funcs = {}, {}
    for f in files:
        al, fn = parse_rc(f)
        aliases.update(al); funcs.update(fn)
    if a.live:
        try:
            aliases.update(live_aliases(a.shell))
        except Exception as e:
            print("aliaslist: live shell query failed: %s" % e, file=sys.stderr)
    show_a = not a.functions
    show_f = not a.aliases
    if show_a:
        print("aliases (%d):" % len(aliases))
        for k in sorted(aliases):
            print("  %-20s %s" % (k, aliases[k]))
    if show_f:
        print("functions (%d):" % len(funcs))
        for k in sorted(funcs):
            print("  %-20s %s" % (k, funcs[k]))
    if not aliases and not funcs:
        print("aliaslist: no aliases or functions found in %s" % ", ".join(files))
    return 0

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