#!/usr/bin/env python3
"""etsy-photo-check.py: before you upload, print each JPEG's bytes, stored pixel size, EXIF
orientation ("none" when the file has no orientation tag), upright size and two yes/no checks against the Etsy Help Center figures read on
2026-11-30: shortest side at least 2000 px (Etsy: 2000 or more recommended, 635 for the first
photo at the very least), and under 1,000,000 bytes (Etsy says images
larger than 1MB may not finish uploading; 1,000,000 bytes is the stricter reading of 1MB).
Standard library only. Exit code 0 when every file passes both checks, 1 otherwise.
Usage:
  python3 etsy-photo-check.py photo1.jpg photo2.jpg ...
  python3 etsy-photo-check.py .              (a folder: every .jpg and .jpeg in it, any letter case)
  python3 etsy-photo-check.py @list.txt     (one path per line; Windows line breaks are fine)
  A shell pattern such as *.jpg is case-sensitive and skips IMG_0001.JPG and photo.jpeg; in zsh
  (the macOS default) a pattern that matches nothing stops the command. Give the folder instead.
"""
import os
import struct
import sys


def jpeg_info(data):
    """Return (width, height, exif_orientation or None) from the first SOF0/1/2 frame, or None."""
    if data[:2] != b"\xff\xd8":
        return None
    i, w, h, orient = 2, None, None, None
    while i + 4 <= len(data):
        if data[i] != 0xFF:
            i += 1
            continue
        m = data[i + 1]
        if m == 0xFF:
            i += 1
            continue
        if m in (0xD8, 0x01) or 0xD0 <= m <= 0xD7:
            i += 2
            continue
        seg_len = struct.unpack(">H", data[i + 2:i + 4])[0]
        seg = data[i + 4:i + 2 + seg_len]
        if m == 0xE1 and seg.startswith(b"Exif\x00\x00") and len(seg) > 14:
            t = seg[6:]
            e = "<" if t[:2] == b"II" else ">"
            try:
                off = struct.unpack(e + "I", t[4:8])[0]
                for k in range(struct.unpack(e + "H", t[off:off + 2])[0]):
                    base = off + 2 + 12 * k
                    if struct.unpack(e + "H", t[base:base + 2])[0] == 0x0112:
                        orient = struct.unpack(e + "H", t[base + 8:base + 10])[0]
            except struct.error:
                pass
        if m in (0xC0, 0xC1, 0xC2) and w is None and len(seg) >= 5:
            h, w = struct.unpack(">HH", seg[1:5])
        if m == 0xDA:
            break
        i += 2 + seg_len
    return (w, h, orient) if w else None


def paths(args):
    for a in args:
        if os.path.isdir(a):
            found = sorted(n for n in os.listdir(a) if n.lower().endswith((".jpg", ".jpeg")))
            if not found:
                yield ("no .jpg or .jpeg files", a)
            for n in found:
                yield os.path.join(a, n)
        elif a.startswith("@"):
            if not os.path.isfile(a[1:]):
                yield ("missing list", a[1:])
                continue
            with open(a[1:], encoding="utf-8-sig", newline="") as f:
                for line in f.read().splitlines():
                    if line.strip():
                        yield line.strip()
        else:
            yield a


def main():
    if len(sys.argv) < 2:
        print(__doc__.strip())
        return 2
    bad = 0
    print("file | bytes | stored | orientation | upright | short_side_2000 | under_1000000_bytes")
    for p in paths(sys.argv[1:]):
        if isinstance(p, tuple):
            print(f"{p[1]} | {p[0]}")
            bad += 1
            continue
        if not os.path.isfile(p):
            hint = " (no file matches this pattern; patterns are case-sensitive; give the folder instead)" if "*" in p else ""
            print(f"{p} | missing{hint}")
            bad += 1
            continue
        size = os.path.getsize(p)
        if size == 0:
            print(f"{p} | 0 | empty file")
            bad += 1
            continue
        with open(p, "rb") as f:
            info = jpeg_info(f.read())
        if not info:
            print(f"{p} | {size} | not a JPEG (no SOF0/1/2 frame)")
            bad += 1
            continue
        w, h, o = info
        uw, uh = (h, w) if o in (5, 6, 7, 8) else (w, h)
        ok_px = min(uw, uh) >= 2000
        ok_b = size < 1_000_000
        bad += (not ok_px) + (not ok_b)
        print(f"{p} | {size} | {w}x{h} | {'none' if o is None else o} | {uw}x{uh} | {'yes' if ok_px else 'no'} | {'yes' if ok_b else 'no'}")
    return 1 if bad else 0


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