#!/usr/bin/env python3
"""cacheclean - clear user caches safely (~/.cache, pip, npm) with sizes reclaimed.
Usage: cacheclean [--clean] [--dry-run] [--home DIR] [--selftest]
Default is a dry run: it lists what would go and how much it would free.
Pass --clean to actually remove it. Never touches anything outside the
known cache locations, and never follows symlinks out of them."""
import argparse, os, shutil, sys

CACHE_DIRS = [".cache", ".npm", ".cache/pip", ".cache/yarn", ".gradle/caches",
              ".cargo/registry/cache", ".cache/go-build"]

def dir_size(path):
    total = 0
    for root, _dirs, files in os.walk(path):
        for name in files:
            try:
                total += os.lstat(os.path.join(root, name)).st_size
            except OSError:
                pass
    return total

def human(n):
    for u in ("B", "K", "M", "G", "T"):
        if abs(n) < 1024 or u == "T":
            return f"{n:.1f}{u}" if u != "B" else f"{int(n)}B"
        n /= 1024.0
    return f"{n:.1f}T"

def scan(home):
    found = []
    for rel in CACHE_DIRS:
        p = os.path.join(home, rel)
        if os.path.isdir(p) and not os.path.islink(p):
            found.append((rel, dir_size(p), p))
    return found

def clean(home, dry_run=True):
    found = scan(home)
    total = sum(sz for _, sz, _ in found)
    removed = []
    if not dry_run:
        for rel, sz, p in found:
            shutil.rmtree(p, ignore_errors=True)
            removed.append((rel, sz))
    return found, total, removed

def selftest():
    import tempfile
    home = tempfile.mkdtemp(prefix="cacheclean-test-")
    os.makedirs(os.path.join(home, ".cache", "pip"))
    os.makedirs(os.path.join(home, ".npm"))
    with open(os.path.join(home, ".cache", "pip", "x"), "wb") as f:
        f.write(b"y" * 1000)
    with open(os.path.join(home, ".npm", "y"), "wb") as f:
        f.write(b"z" * 500)
    found, total, _ = clean(home, dry_run=True)
    ok = True
    if total < 1500:
        print(f"FAIL: dry-run total {total} < 1500"); ok = False
    found2, total2, removed = clean(home, dry_run=False)
    if total2 < 1500:
        print(f"FAIL: clean total {total2} < 1500"); ok = False
    if os.path.exists(os.path.join(home, ".cache", "pip", "x")):
        print("FAIL: cache file survived --clean"); ok = False
    # nothing outside the cache dirs may be touched
    with open(os.path.join(home, "keep.txt"), "w") as f:
        f.write("keep")
    clean(home, dry_run=False)
    if not os.path.exists(os.path.join(home, "keep.txt")):
        print("FAIL: unrelated file removed"); ok = False
    shutil.rmtree(home, ignore_errors=True)
    if ok:
        print("selftest: PASS (dry-run sized 1500B, --clean reclaimed it, unrelated file kept)")
    return 0 if ok else 1

def main():
    ap = argparse.ArgumentParser(prog="cacheclean",
        description="Clear user caches safely (~/.cache, pip, npm) with sizes reclaimed.")
    ap.add_argument("--clean", action="store_true", help="actually remove the caches (default: dry run)")
    ap.add_argument("--dry-run", action="store_true", help="only list what would be removed")
    ap.add_argument("--home", default=os.path.expanduser("~"), help="home directory to clean (default: $HOME)")
    ap.add_argument("--selftest", action="store_true", help="run built-in checks in a temp home")
    a = ap.parse_args()
    if a.selftest:
        return selftest()
    dry = not a.clean or a.dry_run
    found, total, removed = clean(a.home, dry_run=dry)
    if not found:
        print("no user caches found - nothing to clean.")
        return 0
    for rel, sz, _p in found:
        print(f"{human(sz):>10}  ~/{rel}")
    print(f"{human(total):>10}  total")
    if dry:
        print(f"\nDry run - nothing removed. Re-run with --clean to reclaim {human(total)}.")
    else:
        print(f"\nReclaimed {human(total)} from {len(removed)} cache location(s).")
    return 0

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