#!/usr/bin/env python3
import argparse
import glob
import os
import shutil
import subprocess
import tempfile
from pathlib import Path


def find_browser() -> str:
    # Playwright Chromium (most reliable on this workstation)
    for pw in sorted(glob.glob(os.path.expanduser('~/.cache/ms-playwright/chromium-*/chrome-linux/chrome')), reverse=True):
        if os.access(pw, os.X_OK):
            return pw
    for name in ['chromium-browser', 'chromium', 'google-chrome', 'google-chrome-stable']:
        path = shutil.which(name)
        if path:
            return path
    raise SystemExit('No supported browser found for PDF export. Install Playwright Chromium: npx playwright install chromium')


def main() -> int:
    parser = argparse.ArgumentParser(description='Export deck HTML to PDF using headless Chromium')
    parser.add_argument('--html', required=True)
    parser.add_argument('--pdf', required=True)
    args = parser.parse_args()

    html_path = Path(args.html).expanduser().resolve()
    pdf_path = Path(args.pdf).expanduser().resolve()
    pdf_path.parent.mkdir(parents=True, exist_ok=True)

    if not html_path.exists():
        raise SystemExit(f'Missing HTML input: {html_path}')

    browser = find_browser()
    with tempfile.TemporaryDirectory(prefix='rtps-chromium-') as profile_dir:
        cmd = [
            browser,
            '--headless',
            '--disable-gpu',
            '--no-sandbox',
            f'--user-data-dir={profile_dir}',
            f'--print-to-pdf={pdf_path}',
            html_path.as_uri(),
        ]
        subprocess.run(cmd, check=True)
    print(str(pdf_path))
    return 0


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