from __future__ import annotations

import math
import sys
from pathlib import Path

from PIL import Image, ImageDraw, ImageFont


WORK_DIR = Path("/Users/hedy/Desktop/zhct/zhctprompt/product_software_copyright/locker-pickup-source-20260520")
CLEAN_TEXT_PATH = WORK_DIR / "selected_source.clean.txt"
OUT_DIR = WORK_DIR / "rendered_pages"
CONTACT_SHEET = OUT_DIR / "contact-sheet-30-pages.png"
LINES_PER_PAGE = 42
PAGE_COUNT = 30


def load_font(size: int) -> ImageFont.FreeTypeFont | ImageFont.ImageFont:
    for candidate in (
        "/System/Library/Fonts/Supplemental/Songti.ttc",
        "/System/Library/Fonts/STHeiti Light.ttc",
        "/System/Library/Fonts/Menlo.ttc",
        "/System/Library/Fonts/Supplemental/Courier New.ttf",
    ):
        try:
            return ImageFont.truetype(candidate, size=size)
        except Exception:
            continue
    return ImageFont.load_default()


def render_pages(lines: list[str]) -> list[Path]:
    OUT_DIR.mkdir(parents=True, exist_ok=True)
    page_paths: list[Path] = []
    width, height = 1600, 2263
    margin_x, margin_y = 60, 60
    line_height = 30
    font = load_font(16)
    for page_index in range(PAGE_COUNT):
        image = Image.new("RGB", (width, height), "white")
        draw = ImageDraw.Draw(image)
        start = page_index * LINES_PER_PAGE
        page_lines = lines[start : start + LINES_PER_PAGE]
        for offset, line in enumerate(page_lines):
            y = margin_y + offset * line_height
            draw.text((margin_x, y), line, fill=(20, 24, 28), font=font)
        page_path = OUT_DIR / f"page-{page_index + 1:02d}.png"
        image.save(page_path)
        page_paths.append(page_path)
    return page_paths


def make_contact_sheet(page_paths: list[Path]) -> None:
    thumbs = []
    thumb_w = 300
    thumb_h = 424
    label_h = 28
    label_font = load_font(18)
    for idx, path in enumerate(page_paths, start=1):
        image = Image.open(path).convert("RGB")
        image.thumbnail((thumb_w, thumb_h), Image.Resampling.LANCZOS)
        cell = Image.new("RGB", (thumb_w, thumb_h + label_h), "white")
        x = (thumb_w - image.width) // 2
        cell.paste(image, (x, 0))
        draw = ImageDraw.Draw(cell)
        draw.text((8, thumb_h + 3), f"Page {idx:02d}", fill=(0, 0, 0), font=label_font)
        thumbs.append(cell)
    cols = 5
    rows = math.ceil(len(thumbs) / cols)
    sheet = Image.new("RGB", (cols * thumb_w, rows * (thumb_h + label_h)), "white")
    for idx, cell in enumerate(thumbs):
        row = idx // cols
        col = idx % cols
        sheet.paste(cell, (col * thumb_w, row * (thumb_h + label_h)))
    sheet.save(CONTACT_SHEET)


def main() -> None:
    lines = CLEAN_TEXT_PATH.read_text(encoding="utf-8").splitlines()
    expected = LINES_PER_PAGE * PAGE_COUNT
    if len(lines) != expected:
        raise SystemExit(f"expected {expected} lines, got {len(lines)}")
    page_paths = render_pages(lines)
    make_contact_sheet(page_paths)
    print(f"rendered {len(page_paths)} pages")
    print(CONTACT_SHEET)


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