#!/usr/bin/env python3
"""Render an AI流程再造解决方案 HTML file to PDF with the golden-sample settings."""

from __future__ import annotations

import argparse
from pathlib import Path

from playwright.sync_api import sync_playwright


DEFAULT_CHROME = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"


def render_pdf(html_path: Path, pdf_path: Path, screenshot_path: Path | None = None) -> None:
    html_path = html_path.resolve()
    pdf_path = pdf_path.resolve()
    pdf_path.parent.mkdir(parents=True, exist_ok=True)

    with sync_playwright() as p:
        browser = p.chromium.launch(executable_path=DEFAULT_CHROME, headless=True)
        page = browser.new_page(viewport={"width": 1240, "height": 1754}, device_scale_factor=1)
        page.goto(html_path.as_uri(), wait_until="networkidle")
        page.emulate_media(media="print")
        page.pdf(
            path=str(pdf_path),
            format="A4",
            print_background=True,
            prefer_css_page_size=True,
            margin={"top": "0", "right": "0", "bottom": "0", "left": "0"},
        )

        if screenshot_path:
            screenshot_path = screenshot_path.resolve()
            screenshot_path.parent.mkdir(parents=True, exist_ok=True)
            page.evaluate("window.scrollTo(0, document.body.scrollHeight)")
            page.screenshot(path=str(screenshot_path), full_page=False)

        browser.close()


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("html", help="Input HTML file")
    parser.add_argument("pdf", help="Output PDF file")
    parser.add_argument("--screenshot", help="Optional screenshot of the final viewport")
    args = parser.parse_args()

    render_pdf(
        Path(args.html),
        Path(args.pdf),
        Path(args.screenshot) if args.screenshot else None,
    )


if __name__ == "__main__":
    main()
