#!/usr/bin/env python3
"""Export presentation.html as PDF using Chrome headless and Reveal.js print mode."""

import subprocess
import sys
from pathlib import Path

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


def find_chrome():
    for p in CHROME_PATHS:
        if Path(p).exists():
            return p
    return None


def main():
    script_dir = Path(__file__).resolve().parent
    html_path = script_dir / "presentation.html"
    output_path = script_dir / "presentation.pdf"

    if not html_path.exists():
        print(f"Error: {html_path} not found")
        sys.exit(1)

    chrome = find_chrome()
    if not chrome:
        print("Error: Chrome not found. Searched:")
        for p in CHROME_PATHS:
            print(f"  {p}")
        sys.exit(1)

    # Use ?print-pdf to trigger Reveal.js print layout
    file_url = f"file://{html_path}?print-pdf"

    print(f"Using: {chrome}")
    print(f"Opening: {file_url}")
    print("Generating PDF...")

    result = subprocess.run(
        [
            chrome,
            "--headless=new",
            "--disable-gpu",
            "--no-sandbox",
            "--disable-extensions",
            f"--print-to-pdf={output_path}",
            "--print-to-pdf-no-header",
            "--no-pdf-header-footer",
            "--run-all-compositor-stages-before-draw",
            "--virtual-time-budget=10000",
            file_url,
        ],
        capture_output=True,
        text=True,
        timeout=30,
    )

    if output_path.exists():
        size_kb = output_path.stat().st_size / 1024
        print(f"PDF saved to: {output_path} ({size_kb:.0f} KB)")
    else:
        print("Error: PDF was not generated")
        if result.stderr:
            print(result.stderr)
        sys.exit(1)


if __name__ == "__main__":
    main()
