#!/usr/bin/env python3
"""emptyhunt - find empty directories deepest-first, report and optionally remove.
Usage: emptyhunt [dir] [--remove] [--min-depth N] [--selftest] [--help]
Lists directories containing no files (directly or anywhere below), deepest
first so a parent is only listed after its children — the order that makes
removal safe. --remove deletes them (deepest first) and reports the count.
A directory holding only empty subdirectories counts as empty.
"""
import argparse, os, sys, tempfile
from pathlib import Path

def is_empty_tree(p):
    for dp, dns, fns in os.walk(p):
        if fns:
            return False
    return True

def find_empty(root, min_depth=0):
    found = []
    for dp, dns, fns in os.walk(root):
        d = Path(dp)
        depth = len(d.relative_to(root).parts) if d != root else 0
        if depth >= min_depth and is_empty_tree(d):
            found.append((depth, d))
    found.sort(key=lambda t: -t[0])
    return [d for _, d in found]

def selftest():
    with tempfile.TemporaryDirectory() as td:
        base = Path(td)
        (base / "a" / "b" / "c").mkdir(parents=True)
        (base / "a" / "keep").mkdir(parents=True)
        (base / "a" / "keep" / "f.txt").write_text("x")
        (base / "empty1").mkdir()
        (base / "nonempty").mkdir()
        (base / "nonempty" / "f.txt").write_text("y")
        found = find_empty(base)
        names = [str(p.relative_to(base)) for p in found]
        assert "a/b/c" in names and "a/b" in names and "empty1" in names, names
        assert "a" not in names and "nonempty" not in names, names
        # deepest first: c before b
        assert names.index("a/b/c") < names.index("a/b"), names
        print(f"selftest OK: found {len(found)} empty dirs deepest-first, kept non-empty ones")
        return 0

def main():
    ap = argparse.ArgumentParser(description="emptyhunt - find empty directories deepest-first")
    ap.add_argument("dir", nargs="?", default=".")
    ap.add_argument("--remove", action="store_true", help="delete the empty directories found")
    ap.add_argument("--min-depth", type=int, default=0)
    ap.add_argument("--selftest", action="store_true")
    a = ap.parse_args()
    if a.selftest:
        return selftest()
    root = Path(a.dir)
    if not root.is_dir():
        print(f"emptyhunt: {a.dir}: not a directory", file=sys.stderr); return 2
    found = find_empty(root, a.min_depth)
    if not found:
        print("no empty directories"); return 0
    for d in found:
        print(d)
    print(f"{len(found)} empty director(ies)")
    if a.remove:
        n = 0
        for d in found:
            try:
                d.rmdir(); n += 1
            except OSError as e:
                print(f"could not remove {d}: {e}", file=sys.stderr)
        print(f"removed {n} director(ies)")
    return 0

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