#!/usr/bin/env python3
"""exifsort - sort photos into YYYY/MM folders by EXIF/date, dry-run first.
Usage: exifsort [dir] [--dry-run] [--move] [--selftest] [--help]
Reads JPEG EXIF DateTimeOriginal (and PNG/JPEG APP segments fallbacks), else
falls back to the file's modification time, and groups photos under
<dir>/YYYY/MM/. Default is --dry-run: prints the plan and moves nothing.
--move performs the moves. Files with no usable date go to <dir>/unknown/.
No EXIF library needed: minimal JPEG APP1/TIFF parser written here.
"""
import argparse, os, struct, sys, tempfile, time
from pathlib import Path

IMG_EXTS = {".jpg", ".jpeg", ".png", ".tif", ".tiff", ".heic", ".webp", ".gif"}

def jpeg_exif_date(data):
    """Return b'YYYY:MM:DD HH:MM:SS' from JPEG APP1 EXIF, or None."""
    if len(data) < 4 or data[:2] != b"\xff\xd8":
        return None
    i = 2
    while i + 4 < len(data):
        if data[i] != 0xFF:
            break
        marker = data[i + 1]
        if marker in (0xD8, 0xD9) or 0xD0 <= marker <= 0xD7:
            i += 2; continue
        seglen = struct.unpack(">H", data[i + 2:i + 4])[0]
        seg = data[i + 4:i + 2 + seglen]
        if marker == 0xE1 and seg[:6] == b"Exif\x00\x00":
            return tiff_date(seg[6:])
        i += 2 + seglen
    return None

def tiff_date(t):
    if len(t) < 8:
        return None
    endian = "<" if t[:2] == b"II" else ">" if t[:2] == b"MM" else None
    if not endian:
        return None
    off = struct.unpack(endian + "I", t[4:8])[0]
    if off + 2 > len(t):
        return None
    n = struct.unpack(endian + "H", t[off:off + 2])[0]
    for k in range(n):
        e = t[off + 2 + k * 12: off + 2 + (k + 1) * 12]
        if len(e) < 12:
            break
        tag, typ, cnt = struct.unpack(endian + "HHI", e[:8])
        if tag == 0x9003:  # DateTimeOriginal
            valoff = struct.unpack(endian + "I", e[8:12])[0]
            raw = t[valoff:valoff + cnt - 1] if cnt > 4 else e[8:8 + cnt - 1]
            return raw
    return None

def photo_date(p):
    try:
        data = p.read_bytes()[:1 << 20]
    except OSError:
        return None
    raw = jpeg_exif_date(data)
    if raw:
        try:
            s = raw.decode("ascii").strip()
            tm = time.strptime(s, "%Y:%m:%d %H:%M:%S")
            return time.strftime("%Y/%m", tm)
        except (ValueError, UnicodeDecodeError):
            pass
    return None

def selftest():
    with tempfile.TemporaryDirectory() as td:
        base = Path(td)
        # minimal JPEG with EXIF DateTimeOriginal 2021:06:15 10:00:00
        # Build TIFF: II, magic 42, IFD0 offset 8, 1 entry tag 0x9003 ASCII count 20, value offset 26
        date = b"2021:06:15 10:00:00\x00"
        tiff = b"II*\x00" + struct.pack("<I", 8)
        tiff += struct.pack("<H", 1)
        tiff += struct.pack("<HHI", 0x9003, 2, 20) + struct.pack("<I", 8 + 2 + 12 + 4)
        tiff += struct.pack("<I", 0)
        tiff += date
        exif = b"Exif\x00\x00" + tiff
        app1 = b"\xff\xe1" + struct.pack(">H", len(exif) + 2) + exif
        jpg = b"\xff\xd8" + app1 + b"\xff\xd9"
        (base / "photo.jpg").write_bytes(jpg)
        (base / "nodate.png").write_bytes(b"\x89PNG\r\n\x1a\n" + b"\x00" * 100)
        os.utime(base / "nodate.png", (1600000000, 1600000000))  # 2020-09-13
        import subprocess
        r = subprocess.run([sys.executable, __file__, str(base), "--move"],
                           capture_output=True, text=True)
        assert r.returncode == 0, r.stderr
        assert (base / "2021" / "06" / "photo.jpg").exists(), r.stdout
        assert (base / "2020" / "09" / "nodate.png").exists(), r.stdout
        print("selftest OK: EXIF photo -> 2021/06, dateless photo fell back to mtime -> 2020/09")
        return 0

def main():
    ap = argparse.ArgumentParser(description="exifsort - sort photos into YYYY/MM folders by EXIF/date")
    ap.add_argument("dir", nargs="?", default=".")
    ap.add_argument("--dry-run", action="store_true", help="print the plan, move nothing (default)")
    ap.add_argument("--move", action="store_true", help="actually move the files")
    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"exifsort: {a.dir}: not a directory", file=sys.stderr); return 2
    do_move = a.move
    if not do_move and not a.dry_run:
        print("dry-run (default): use --move to actually move files")
    moves = []
    for p in sorted(root.rglob("*")):
        if not p.is_file() or p.suffix.lower() not in IMG_EXTS:
            continue
        # skip files already inside a YYYY/MM folder
        rel = p.relative_to(root)
        if len(rel.parts) >= 3 and rel.parts[0].isdigit() and len(rel.parts[0]) == 4 and rel.parts[1].isdigit():
            continue
        ym = photo_date(p)
        if ym is None:
            tm = time.localtime(p.stat().st_mtime)
            ym = time.strftime("%Y/%m", tm)
        dest = root / ym / p.name
        if dest == p:
            continue
        moves.append((p, dest))
    if not moves:
        print("nothing to sort"); return 0
    for src, dst in moves:
        print(f"{src} -> {dst}")
    if not do_move:
        print(f"dry-run: {len(moves)} move(s), nothing changed (use --move)"); return 0
    for src, dst in moves:
        dst.parent.mkdir(parents=True, exist_ok=True)
        target = dst
        i = 1
        while target.exists():
            target = dst.with_name(f"{dst.stem}_{i}{dst.suffix}"); i += 1
        src.rename(target)
    print(f"moved {len(moves)} photo(s)")
    return 0

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