#!/usr/bin/env python3
"""
jpgs_to_pdf.py

Converts a folder of .jpg images into a single PDF, one image per page,
in filename order (so 00.jpg, 01.jpg, 02.jpg, ... end up in that order).

Usage:
    python3 jpgs_to_pdf.py input_dir [output.pdf]

If output.pdf is omitted, it defaults to "output.pdf" inside input_dir's
parent, i.e. saved next to the input folder.
"""

import os
import sys

from PIL import Image


def main():
    if len(sys.argv) < 2:
        print("Usage: python3 jpgs_to_pdf.py input_dir [output.pdf]")
        sys.exit(1)

    input_dir = sys.argv[1]
    if not os.path.isdir(input_dir):
        print(f"Error: not a directory: {input_dir}")
        sys.exit(1)

    if len(sys.argv) > 2:
        output_path = sys.argv[2]
    else:
        output_path = "output.pdf"

    # Collect .jpg/.jpeg files and sort by filename so 00.jpg, 01.jpg, ... order correctly
    files = [
        f for f in os.listdir(input_dir)
        if f.lower().endswith((".jpg", ".jpeg"))
    ]
    files.sort()

    if not files:
        print(f"No .jpg files found in {input_dir}")
        sys.exit(1)

    images = []
    for fname in files:
        path = os.path.join(input_dir, fname)
        img = Image.open(path)
        # PDF doesn't support RGBA/P modes, convert to RGB
        if img.mode != "RGB":
            img = img.convert("RGB")
        images.append(img)
        print(f"Added {fname}")

    first, rest = images[0], images[1:]
    first.save(output_path, save_all=True, append_images=rest)

    print(f"\nDone. Saved {len(images)} page(s) to '{output_path}'.")


if __name__ == "__main__":
    main()
