import sys
from pathlib import Path

from pdf2image import convert_from_path
from pdf2image.exceptions import PDFInfoNotInstalledError


# Converts each page of a PDF to a PNG image.


def convert(pdf_path, output_dir, max_dim=1000):
    output_path = Path(output_dir)
    output_path.mkdir(parents=True, exist_ok=True)

    try:
        images = convert_from_path(pdf_path, dpi=200)
    except PDFInfoNotInstalledError:
        raise RuntimeError(
            "Poppler is required. Install Poppler and ensure `pdfinfo` is available in PATH."
        )

    for i, image in enumerate(images):
        # Scale image if needed to keep width/height under `max_dim`
        width, height = image.size
        if width > max_dim or height > max_dim:
            scale_factor = min(max_dim / width, max_dim / height)
            new_width = int(width * scale_factor)
            new_height = int(height * scale_factor)
            image = image.resize((new_width, new_height))

        image_path = output_path / f"page_{i+1}.png"
        image.save(str(image_path))
        print(f"Saved page {i+1} as {image_path} (size: {image.size})")

    print(f"Converted {len(images)} pages to PNG images")


def main(argv: list[str] | None = None) -> int:
    args = argv if argv is not None else sys.argv[1:]
    if len(args) != 2:
        print("Usage: convert_pdf_to_images.py [input pdf] [output directory]")
        return 1

    pdf_path = args[0]
    output_directory = args[1]
    try:
        convert(pdf_path, output_directory)
        return 0
    except RuntimeError as exc:
        print(str(exc), file=sys.stderr)
        return 1


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