from __future__ import annotations

import argparse
import math
from pathlib import Path

from PIL import Image, ImageDraw, ImageFont


ROOT = Path(__file__).resolve().parent
PAGES = ROOT / "tmp" / "pdfs" / "current"
OUTPUT = ROOT / "tmp" / "pdfs" / "contact"


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--pages", default=str(PAGES))
    parser.add_argument("--output", default=str(OUTPUT))
    args = parser.parse_args()
    pages_dir = Path(args.pages).resolve()
    output_dir = Path(args.output).resolve()
    pages = sorted(pages_dir.glob("page-*.png"))
    if not pages:
        raise FileNotFoundError("rendered pages are missing")
    output_dir.mkdir(parents=True, exist_ok=True)
    for old in output_dir.glob("contact-*.jpg"):
        old.unlink()
    per_sheet = 6
    for sheet_index in range(math.ceil(len(pages) / per_sheet)):
        subset = pages[sheet_index * per_sheet:(sheet_index + 1) * per_sheet]
        canvas = Image.new("RGB", (1800, 2200), "#d8d2ca")
        draw = ImageDraw.Draw(canvas)
        for position, path in enumerate(subset):
            with Image.open(path) as source:
                page = source.convert("RGB")
                page.thumbnail((560, 990), Image.Resampling.LANCZOS)
            column = position % 3
            row = position // 3
            x = 25 + column * 590 + (560 - page.width) // 2
            y = 55 + row * 1070
            canvas.paste(page, (x, y))
            draw.text((35 + column * 590, 20 + row * 1070), f"Page {sheet_index * per_sheet + position + 1}", fill="#251b16")
        canvas.save(output_dir / f"contact-{sheet_index + 1:02d}.jpg", quality=90)
    print(f"created {math.ceil(len(pages) / per_sheet)} contact sheets for {len(pages)} pages")


if __name__ == "__main__":
    main()
