#!/usr/bin/env python3
"""nestcount - count files by depth level in a tree (how deep is the mess?).
Usage: nestcount [dir] [--max-depth N] [--bar] [--selftest] [--help]
Counts files (and optionally directories) at each depth below <dir>, and
prints a table with a bar chart. The depth profile answers "how deep is the
mess" at a glance: a healthy tree is shallow, a hoarder's tree has a long
tail. --max-depth caps the walk.
"""
import argparse, os, sys, tempfile
from pathlib import Path
from collections import Counter

def count_depths(root, max_depth=None):
    files = Counter(); dirs = Counter()
    for dp, dns, fns in os.walk(root):
        d = Path(dp)
        depth = 0 if d == root else len(d.relative_to(root).parts)
        if max_depth is not None and depth > max_depth:
            dns[:] = []
            continue
        dirs[depth] += 1
        files[depth] += len(fns)
    return files, dirs

def selftest():
    with tempfile.TemporaryDirectory() as td:
        base = Path(td)
        (base / "a.txt").write_text("x")
        (base / "d1").mkdir(); (base / "d1" / "b.txt").write_text("x")
        (base / "d1" / "d2").mkdir(); (base / "d1" / "d2" / "c.txt").write_text("x")
        (base / "d1" / "d2" / "d.txt").write_text("x")
        files, dirs = count_depths(base)
        assert files[0] == 1 and files[1] == 1 and files[2] == 2, dict(files)
        assert max(files) == 2
        print("selftest OK: depths 0/1/2 hold 1/1/2 files, max depth 2")
        return 0

def main():
    ap = argparse.ArgumentParser(description="nestcount - count files by depth level in a tree")
    ap.add_argument("dir", nargs="?", default=".")
    ap.add_argument("--max-depth", type=int, default=None)
    ap.add_argument("--bar", action="store_true", help="draw a bar chart (default on for TTY)")
    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"nestcount: {a.dir}: not a directory", file=sys.stderr); return 2
    files, dirs = count_depths(root, a.max_depth)
    if not files:
        print("no files found"); return 0
    total = sum(files.values())
    deepest = max(files)
    show_bar = a.bar or sys.stdout.isatty()
    print(f"{'DEPTH':>5}  {'FILES':>6}  {'DIRS':>5}  {'%':>5}  {'BAR' if show_bar else ''}")
    peak = max(files.values())
    for depth in sorted(files):
        pct = 100 * files[depth] / total
        bar = "#" * max(1, int(40 * files[depth] / peak)) if show_bar else ""
        print(f"{depth:>5}  {files[depth]:>6}  {dirs[depth]:>5}  {pct:>4.1f}%  {bar}")
    print(f"\n{total} files, deepest level {deepest}")
    deep = sum(v for k, v in files.items() if k >= 5)
    if deep:
        print(f"warning: {deep} file(s) live at depth 5 or deeper — consider flattening")
    return 0

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