#!/usr/bin/env python3
"""Rename photos in a folder by the date they were taken, e.g. 2026-07-04_001.jpg.

Uses the photo's EXIF date when Pillow is installed and the photo has one,
otherwise the file's modified time. Shows what it would do first; add --apply
to rename for real. Never overwrites a file.

    python3 rename_photos.py ~/Pictures/trip            # preview
    python3 rename_photos.py ~/Pictures/trip --apply    # rename
"""
import argparse
import datetime as dt
from pathlib import Path

PHOTO_TYPES = {".jpg", ".jpeg", ".png", ".heic", ".gif", ".webp"}


def taken_date(path):
    try:
        from PIL import Image
        with Image.open(path) as im:
            raw = im.getexif().get(306)  # 306 = DateTime
        if raw:
            return dt.datetime.strptime(raw, "%Y:%m:%d %H:%M:%S")
    except Exception:
        pass
    return dt.datetime.fromtimestamp(path.stat().st_mtime)


def plan(folder):
    photos = sorted((p for p in Path(folder).iterdir()
                     if p.is_file() and p.suffix.lower() in PHOTO_TYPES),
                    key=lambda p: (taken_date(p), p.name))
    counts, moves = {}, []
    taken = {p.name for p in Path(folder).iterdir()}
    for p in photos:
        day = taken_date(p).strftime("%Y-%m-%d")
        while True:
            counts[day] = counts.get(day, 0) + 1
            new = f"{day}_{counts[day]:03d}{p.suffix.lower()}"
            if new == p.name or new not in taken:
                break
        if new != p.name:
            moves.append((p, p.with_name(new)))
            taken.add(new)
    return moves


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    ap.add_argument("folder")
    ap.add_argument("--apply", action="store_true", help="rename for real")
    args = ap.parse_args(argv)
    moves = plan(args.folder)
    for old, new in moves:
        print(f"{old.name}  ->  {new.name}")
        if args.apply:
            old.rename(new)
    verb = "Renamed" if args.apply else "Would rename"
    print(f"{verb} {len(moves)} photo(s).")
    if moves and not args.apply:
        print("Run again with --apply to do it.")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
