#!/usr/bin/env python3
"""oldfiles - files untouched for X days grouped by directory, with size totals and an archive plan.
Usage: oldfiles [dir] [--days N] [--plan] [--selftest] [--help]
Finds files whose mtime is older than N days (default 180), groups them by
their parent directory with per-directory file counts and size totals, and
ranks directories by reclaimable bytes. --plan prints a ready-to-run
`tar` archive command per directory instead of just the report.
"""
import argparse, os, sys, tempfile, time
from pathlib import Path

def human(n):
    for u in ("B", "KiB", "MiB", "GiB", "TiB"):
        if abs(n) < 1024 or u == "TiB":
            return f"{n:.1f} {u}" if u != "B" else f"{n} B"
        n /= 1024

def collect(root, cutoff):
    groups = {}
    for p in root.rglob("*"):
        if p.is_file() and not p.is_symlink():
            try:
                st = p.stat()
            except OSError:
                continue
            if st.st_mtime < cutoff:
                g = groups.setdefault(str(p.parent), {"files": 0, "bytes": 0, "paths": []})
                g["files"] += 1; g["bytes"] += st.st_size; g["paths"].append(str(p))
    return groups

def selftest():
    with tempfile.TemporaryDirectory() as td:
        base = Path(td)
        d1 = base / "oldstuff"; d1.mkdir()
        d2 = base / "fresh"; d2.mkdir()
        old = time.time() - 200 * 86400
        (d1 / "a.bin").write_bytes(b"x" * 500)
        (d1 / "b.bin").write_bytes(b"y" * 300)
        (d2 / "c.bin").write_bytes(b"z" * 100)
        os.utime(d1 / "a.bin", (old, old)); os.utime(d1 / "b.bin", (old, old))
        groups = collect(base, time.time() - 180 * 86400)
        assert len(groups) == 1, groups
        g = groups[str(d1)]
        assert g["files"] == 2 and g["bytes"] == 800, g
        print("selftest OK: 2 old files (800 B) grouped under oldstuff, fresh file excluded")
        return 0

def main():
    ap = argparse.ArgumentParser(description="oldfiles - files untouched for X days, grouped by directory")
    ap.add_argument("dir", nargs="?", default=".")
    ap.add_argument("--days", type=int, default=180)
    ap.add_argument("--plan", action="store_true", help="print tar archive commands per directory")
    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"oldfiles: {a.dir}: not a directory", file=sys.stderr); return 2
    cutoff = time.time() - a.days * 86400
    groups = collect(root, cutoff)
    if not groups:
        print(f"no files older than {a.days} days under {root}"); return 0
    total_f = sum(g["files"] for g in groups.values())
    total_b = sum(g["bytes"] for g in groups.values())
    print(f"files untouched for {a.days}+ days under {root}: {total_f} files, {human(total_b)}")
    for d, g in sorted(groups.items(), key=lambda kv: -kv[1]["bytes"]):
        print(f"{human(g['bytes']):>10}  {g['files']:>4} files  {d}")
        if a.plan:
            arc = Path(d).name + f"-archive-{a.days}d.tar.gz"
            print(f"    tar czf {arc} {' '.join(repr(p) for p in g['paths'][:5])}"
                  + (f" ... ({len(g['paths'])-5} more)" if len(g['paths']) > 5 else ""))
    return 0

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