#!/usr/bin/env python3
"""
export_pdf.py — Render a slide-maker slides.html into a single PDF.

Injects a print stylesheet that shows every .slide (not just .active) as its
own page at the native 16:9 size (13.333in x 7.5in, matching build_pptx.py's
SLIDE_W/SLIDE_H), then runs headless Chrome's --print-to-pdf once. No extra
dependencies beyond a locally installed Google Chrome.

Usage:
  python3 export_pdf.py --html slides.html --output slides.pdf
"""
import argparse
import re
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path

CHROME_CANDIDATES = [
    "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
    "/Applications/Chromium.app/Contents/MacOS/Chromium",
]

PRINT_CSS = """
@media print {
  html, body { margin: 0 !important; padding: 0 !important; background: white !important; }
  @page { size: 13.333in 7.5in; margin: 0; }
  .nav { display: none !important; }
  .stage {
    display: block !important;
    position: static !important;
    transform: none !important;
    width: auto !important; height: auto !important;
  }
  .slide-wrapper {
    width: 13.333in !important; height: auto !important;
    overflow: visible !important; box-shadow: none !important;
  }
  .slide {
    display: block !important;
    width: 13.333in !important; height: 7.5in !important;
    overflow: hidden !important;
    page-break-after: always;
    break-after: page;
  }
  .slide:last-child { page-break-after: auto; break-after: auto; }
}
"""


def find_chrome() -> str:
    for c in CHROME_CANDIDATES:
        if Path(c).exists():
            return c
    found = shutil.which("google-chrome") or shutil.which("chromium")
    if found:
        return found
    sys.exit("エラー: Google Chrome が見つかりません。/Applications にインストールしてください。")


def count_slides(html_text: str) -> int:
    return len(re.findall(r'class="slide"', html_text))


def build(html: Path, output: Path) -> None:
    chrome = find_chrome()
    src = html.read_text(encoding="utf-8")
    n = count_slides(src)
    if n == 0:
        sys.exit(f"エラー: {html} にスライドが見つかりません")

    injected = src.replace("</style>", PRINT_CSS + "</style>", 1)

    with tempfile.NamedTemporaryFile(
        "w", suffix=".html", dir=str(html.parent), delete=False, encoding="utf-8"
    ) as f:
        f.write(injected)
        wrapper = Path(f.name)

    try:
        output.parent.mkdir(parents=True, exist_ok=True)
        subprocess.run(
            [
                chrome, "--headless", "--disable-gpu",
                "--no-pdf-header-footer",
                f"--print-to-pdf={output}",
                f"file://{wrapper}",
            ],
            check=True,
            capture_output=True,
        )
    finally:
        wrapper.unlink(missing_ok=True)

    print(f"OK: {n} slides -> {output}")


def main():
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument("--html", required=True, help="path to slides.html (slide-maker output)")
    ap.add_argument("--output", required=True, help="PDF output path")
    args = ap.parse_args()
    build(Path(args.html).expanduser(), Path(args.output).expanduser())


if __name__ == "__main__":
    main()
