#!/usr/bin/env python3
"""lostfound - digital-hoarding report: files untouched 2+ years and over 100 MB.
Usage: lostfound [dir] [--years N] [--min-size SIZE] [--selftest] [--help]
The hoarding audit: files untouched for N years (default 2) AND larger than
--min-size (default 100 MB), ranked by size, with age, type and the directory
they are squatting in — plus the total bytes that would be freed and the
share of the tree they occupy. These are the files you forgot you had.
"""
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 parse_size(s):
    m = {"K": 1024, "M": 1024 ** 2, "G": 1024 ** 3, "T": 1024 ** 4}
    s = s.strip().upper()
    if s and s[-1] in m:
        return int(float(s[:-1]) * m[s[-1]])
    return int(s)

def find_hoard(root, cutoff, min_size):
    rows, tree_total = [], 0
    for p in root.rglob("*"):
        if p.is_file() and not p.is_symlink():
            try:
                st = p.stat()
            except OSError:
                continue
            tree_total += st.st_size
            if st.st_mtime < cutoff and st.st_size >= min_size:
                rows.append((p, st))
    return rows, tree_total

def selftest():
    with tempfile.TemporaryDirectory() as td:
        base = Path(td)
        old = time.time() - 3 * 365 * 86400
        big = base / "forgotten.iso"
        big.write_bytes(b"\x00" * 2000)
        os.utime(big, (old, old))
        small_old = base / "tiny-old.txt"
        small_old.write_text("x")
        os.utime(small_old, (old, old))
        fresh_big = base / "fresh-big.bin"
        fresh_big.write_bytes(b"\x00" * 2000)
        rows, total = find_hoard(base, time.time() - 2 * 365 * 86400, 1000)
        assert len(rows) == 1 and rows[0][0] == big, rows
        assert total == 2000 + 1 + 2000
        print("selftest OK: 1 hoarded file found (old + big); old-small and fresh-big excluded")
        return 0

def main():
    ap = argparse.ArgumentParser(description="lostfound - digital-hoarding report: old AND large files")
    ap.add_argument("dir", nargs="?", default=".")
    ap.add_argument("--years", type=float, default=2)
    ap.add_argument("--min-size", default="100M")
    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"lostfound: {a.dir}: not a directory", file=sys.stderr); return 2
    cutoff = time.time() - a.years * 365.25 * 86400
    min_size = parse_size(a.min_size)
    rows, tree_total = find_hoard(root, cutoff, min_size)
    if not rows:
        print(f"no files untouched {a.years} year(s) and over {human(min_size)} under {root}")
        print("your hoard is under control (for now)"); return 0
    rows.sort(key=lambda r: -r[1].st_size)
    total = sum(st.st_size for _, st in rows)
    print(f"hoarded files: untouched {a.years} year(s), over {human(min_size)} — "
          f"{len(rows)} file(s), {human(total)} "
          f"({100 * total / tree_total:.1f}% of this tree's {human(tree_total)})")
    print(f"{'SIZE':>10}  {'AGE':>7}  {'TYPE':<8}  PATH")
    for p, st in rows:
        age_y = (time.time() - st.st_mtime) / (365.25 * 86400)
        print(f"{human(st.st_size):>10}  {age_y:>6.1f}y  {p.suffix.lower() or '(none)':<8}  {p}")
    print(f"\ndeleting all of these would free {human(total)}")
    return 0

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