#!/usr/bin/env python3
"""
Generate a JPG thumbnail from the first page of a PDF.
Usage:
    python pdf_to_thumb.py input.pdf output.jpg 600
"""

import sys
import os
from pdf2image import convert_from_path
from PIL import Image


def make_thumbnail(pdf_path, out_path, width):
    if not os.path.exists(pdf_path):
        print(f"❌ Input file not found: {pdf_path}")
        sys.exit(1)

    try:
        # Convert only the first page (requires poppler installed)
        pages = convert_from_path(pdf_path, dpi=144, first_page=1, last_page=1)
        page = pages[0].convert("RGB")

        # Calculate new height preserving aspect ratio
        w, h = page.size
        new_h = int(h * (width / w))

        # Resize and save
        thumb = page.resize((width, new_h), Image.LANCZOS)
        thumb.save(out_path, "JPEG", quality=85, optimize=True)

        print(f"✅ Saved thumbnail: {out_path}")
    except Exception as e:
        print(f"⚠️ Failed to process {pdf_path}: {e}")


if __name__ == "__main__":
    if len(sys.argv) != 4:
        print("Usage: python pdf_to_thumb.py input.pdf output.jpg width")
        sys.exit(1)

    pdf_path = sys.argv[1]
    out_path = sys.argv[2]
    width = int(sys.argv[3])

    make_thumbnail(pdf_path, out_path, width)
