"""PDF generation using Playwright (headless Chromium)."""

from __future__ import annotations

from pathlib import Path


def generate_pdf(html_path: Path, output_path: Path) -> Path:
    """
    Generate a PDF from a PagedJS-rendered HTML file.

    Launches headless Chromium, waits for PagedJS to finish rendering,
    then exports the page as PDF.

    Args:
        html_path: Absolute path to the print HTML file.
        output_path: Absolute path for the generated PDF.

    Returns:
        Path to the generated PDF file.

    Raises:
        RuntimeError: If playwright is not installed.
    """
    try:
        from playwright.sync_api import sync_playwright
    except ImportError:
        raise RuntimeError(
            "PDF generation requires Playwright.\n"
            "Install it with: pip install mkbooks[pdf]\n"
            "Then run: playwright install chromium"
        )

    file_url = html_path.as_uri()

    with sync_playwright() as p:
        browser = p.chromium.launch()
        page = browser.new_page()
        page.goto(file_url, wait_until="load")

        # Wait for PagedJS to finish rendering (creates .pagedjs_pages element)
        page.wait_for_selector(".pagedjs_pages", timeout=60_000)
        # Give PagedJS a moment to finalize layout
        page.wait_for_timeout(1_000)

        page.pdf(
            path=str(output_path),
            prefer_css_page_size=True,
            print_background=True,
        )

        browser.close()

    return output_path
