#!/usr/bin/env python3
"""treeclean - remove common junk (thumbs.db, .DS_Store, *~, __pycache__) with a preview and count.
Usage: treeclean [dir] [--dry-run] [--apply] [--extra PATTERN ...] [--selftest] [--help]
Finds junk files and directories (Thumbs.db, .DS_Store, desktop.ini, *~,
*.bak, *.tmp, *.swp, __pycache__, .pytest_cache, node_modules/.cache, *.pyc),
reports the count and reclaimable bytes, and with --apply deletes them.
Default is a preview. --extra adds glob patterns of your own.
"""
import argparse, fnmatch, os, shutil, sys, tempfile
from pathlib import Path

JUNK_FILES = ["Thumbs.db", ".DS_Store", "desktop.ini", "*~", "*.bak", "*.tmp",
              "*.swp", "*.swo", "*.pyc", "*.pyo", ".directory"]
JUNK_DIRS = ["__pycache__", ".pytest_cache", ".mypy_cache", ".ruff_cache",
             "node_modules/.cache", ".cache"]

def is_junk(p):
    if p.is_dir():
        return p.name in JUNK_DIRS or "/".join(p.parts[-2:]) in JUNK_DIRS
    return any(fnmatch.fnmatchcase(p.name, pat) for pat in JUNK_FILES)

def selftest():
    with tempfile.TemporaryDirectory() as td:
        base = Path(td)
        (base / ".DS_Store").write_bytes(b"x" * 10)
        (base / "Thumbs.db").write_bytes(b"x" * 20)
        (base / "notes.txt").write_text("keep me")
        (base / "sub").mkdir()
        (base / "sub" / "__pycache__").mkdir()
        (base / "sub" / "__pycache__" / "mod.pyc").write_bytes(b"y" * 30)
        (base / "sub" / "real.py").write_text("print(1)")
        import subprocess
        r = subprocess.run([sys.executable, __file__, str(base), "--apply"],
                           capture_output=True, text=True)
        assert r.returncode == 0, r.stderr
        assert not (base / ".DS_Store").exists()
        assert not (base / "Thumbs.db").exists()
        assert not (base / "sub" / "__pycache__").exists()
        assert (base / "notes.txt").exists() and (base / "sub" / "real.py").exists()
        print("selftest OK: junk removed (.DS_Store, Thumbs.db, __pycache__), real files kept")
        return 0

def main():
    ap = argparse.ArgumentParser(description="treeclean - remove common junk files with a preview and count")
    ap.add_argument("dir", nargs="?", default=".")
    ap.add_argument("--dry-run", action="store_true")
    ap.add_argument("--apply", action="store_true", help="actually delete the junk")
    ap.add_argument("--extra", nargs="*", default=[], help="extra glob patterns to treat as junk")
    ap.add_argument("--selftest", action="store_true")
    a = ap.parse_args()
    if a.selftest:
        return selftest()
    global JUNK_FILES
    JUNK_FILES = JUNK_FILES + a.extra
    root = Path(a.dir)
    if not root.is_dir():
        print(f"treeclean: {a.dir}: not a directory", file=sys.stderr); return 2
    junk = []
    for dp, dns, fns in os.walk(root, topdown=False):
        d = Path(dp)
        for name in dns:
            p = d / name
            if is_junk(p):
                junk.append(p)
        for name in fns:
            p = d / name
            if is_junk(p):
                junk.append(p)
    # drop children of junk dirs (they go with the parent)
    junk_set = set(junk)
    junk = [p for p in junk if not any(parent in junk_set for parent in p.parents)]
    total = 0
    for p in junk:
        if p.is_file():
            total += p.stat().st_size
        elif p.is_dir():
            total += sum(f.stat().st_size for f in p.rglob("*") if f.is_file())
    for p in sorted(junk):
        print(p)
    print(f"{len(junk)} junk item(s), {total} bytes reclaimable")
    if not a.apply:
        print("preview only; use --apply to delete"); return 0
    n = 0
    for p in junk:
        try:
            if p.is_dir():
                shutil.rmtree(p)
            else:
                p.unlink()
            n += 1
        except OSError as e:
            print(f"could not remove {p}: {e}", file=sys.stderr)
    print(f"removed {n} junk item(s), freed {total} bytes")
    return 0

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