#!/usr/bin/env python3
"""sortbyage - move files into folders by age buckets (today / this week / this month / older).
Usage: sortbyage [dir] [--dry-run] [--apply] [--selftest] [--help]
Moves files (non-recursive, top level of <dir>) into age buckets based on
mtime: `today` (<24h), `this-week` (<7d), `this-month` (<30d), `older`.
Bucket boundaries are configurable with --week-days/--month-days. Default is
a preview; --apply moves. Name clashes get a `_2` suffix.
"""
import argparse, os, sys, tempfile, time
from pathlib import Path

def bucket(age_s, week_days=7, month_days=30):
    if age_s < 86400:
        return "today"
    if age_s < week_days * 86400:
        return "this-week"
    if age_s < month_days * 86400:
        return "this-month"
    return "older"

def selftest():
    with tempfile.TemporaryDirectory() as td:
        base = Path(td)
        now = time.time()
        (base / "new.txt").write_text("n")
        (base / "week.txt").write_text("w")
        (base / "old.txt").write_text("o")
        os.utime(base / "week.txt", (now - 3 * 86400, now - 3 * 86400))
        os.utime(base / "old.txt", (now - 90 * 86400, now - 90 * 86400))
        assert bucket(0) == "today" and bucket(3 * 86400) == "this-week"
        assert bucket(20 * 86400) == "this-month" and bucket(90 * 86400) == "older"
        import subprocess
        r = subprocess.run([sys.executable, __file__, str(base), "--apply"],
                           capture_output=True, text=True)
        assert r.returncode == 0, r.stderr
        assert (base / "today" / "new.txt").exists(), r.stdout
        assert (base / "this-week" / "week.txt").exists(), r.stdout
        assert (base / "older" / "old.txt").exists(), r.stdout
        print("selftest OK: new->today, 3d->this-week, 90d->older")
        return 0

def main():
    ap = argparse.ArgumentParser(description="sortbyage - move files into folders by age buckets")
    ap.add_argument("dir", nargs="?", default=".")
    ap.add_argument("--dry-run", action="store_true")
    ap.add_argument("--apply", action="store_true", help="actually move the files")
    ap.add_argument("--week-days", type=int, default=7)
    ap.add_argument("--month-days", type=int, default=30)
    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"sortbyage: {a.dir}: not a directory", file=sys.stderr); return 2
    now = time.time()
    moves = []
    for p in sorted(root.iterdir()):
        if not p.is_file():
            continue
        b = bucket(now - p.stat().st_mtime, a.week_days, a.month_days)
        moves.append((p, root / b / p.name))
    if not moves:
        print("nothing to sort"); return 0
    for src, dst in moves:
        print(f"{src.name} -> {dst.parent.name}/{dst.name}")
    if not a.apply:
        print(f"preview: {len(moves)} move(s); use --apply to move"); return 0
    for src, dst in moves:
        dst.parent.mkdir(exist_ok=True)
        target = dst
        i = 2
        while target.exists():
            target = dst.with_name(f"{dst.stem}_{i}{dst.suffix}"); i += 1
        src.rename(target)
    print(f"moved {len(moves)} file(s) into age buckets")
    return 0

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