#!/usr/bin/env python3
# pathclean - show PATH entries, flag duplicates and missing directories, print a cleaned PATH
# Usage: pathclean [--path PATH] [--export] [--check]
import argparse, os, sys

def selftest():
    fake = "/tmp:/usr/bin:/tmp:/nonexistent-dir-xyz:/usr/bin"
    out = subprocess.run([sys.executable, os.path.abspath(__file__), "--path", fake],
                         capture_output=True, text=True)
    assert out.returncode == 0, out.stderr
    assert "duplicate" in out.stdout.lower() and "missing" in out.stdout.lower(), out.stdout
    cleaned = [l for l in out.stdout.splitlines() if l.startswith("cleaned:")]
    assert cleaned and cleaned[0].count("/tmp") == 1, out.stdout
    assert "/nonexistent-dir-xyz" not in cleaned[0]
    print("pathclean selftest: PASS")
    return 0

import subprocess

def main():
    ap = argparse.ArgumentParser(prog="pathclean",
        description="Show PATH entries, flag duplicates and missing directories, print a cleaned PATH.")
    ap.add_argument("--path", default=None, help="PATH to inspect (default: $PATH)")
    ap.add_argument("--export", action="store_true", help="print the cleaned PATH as an export statement")
    ap.add_argument("--check", action="store_true", help="only report problems, exit 1 if any")
    ap.add_argument("--selftest", action="store_true", help="run built-in self-test and exit")
    a = ap.parse_args()
    if a.selftest:
        return selftest()
    raw = a.path if a.path is not None else os.environ.get("PATH", "")
    entries = raw.split(":") if raw else []
    seen, cleaned = set(), []
    dups, missing, empty = [], [], 0
    for i, e in enumerate(entries):
        if e == "":
            empty += 1
            continue
        if e in seen:
            dups.append((i, e)); continue
        seen.add(e)
        if not os.path.isdir(e):
            missing.append((i, e))
        else:
            cleaned.append(e)
    print("PATH has %d entries (%d unique, %d usable):" % (len(entries), len(seen), len(cleaned)))
    for i, e in enumerate(entries):
        flags = []
        if e == "":
            flags.append("EMPTY")
        elif any(d[0] == i for d in dups):
            flags.append("DUPLICATE")
        elif any(m[0] == i for m in missing):
            flags.append("MISSING")
        print("  [%2d] %-50s %s" % (i, e or "(empty)", " ".join(flags)))
    if empty:
        print("note: %d empty entr%s (mean current directory — a security smell)" % (empty, "y" if empty == 1 else "ies"))
    clean = ":".join(cleaned)
    if a.export:
        print('export PATH="%s"' % clean)
    else:
        print("cleaned: %s" % clean)
    if a.check:
        return 1 if (dups or missing or empty) else 0
    return 0

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