"""
render_pdf.py

Converts a rendered brand manual HTML file (output of render_brand_manual.py)
into a paginated PDF, one .sheet section per PDF page.

Usage:
    python render_pdf.py --html acme-brand-manual.html --out acme-brand-manual.pdf
"""

import argparse
from pathlib import Path

from playwright.sync_api import sync_playwright

# Injected before printing: forces each .sheet section onto its own PDF page
# and strips the screen-only chrome (tab rail, page shadows, checkerboard bg)
# that only makes sense in the browser preview.
PRINT_CSS = """
<style>
  @media print {
    body { background: white !important; display:block !important; }
    .rail { display:none !important; }
    .doc { padding:0 !important; gap:0 !important; }
    .sheet {
      box-shadow:none !important;
      margin:0 !important;
      page-break-after: always;
      width:100% !important;
      min-height:100vh;
    }
    .sheet:last-child { page-break-after: auto; }
  }
</style>
"""


def render_pdf(html_path, out_path, page_format="Letter"):
    html = Path(html_path).read_text()
    if "</head>" in html:
        html = html.replace("</head>", PRINT_CSS + "</head>")
    else:
        html = PRINT_CSS + html

    tmp_path = Path(html_path).with_suffix(".print.html")
    tmp_path.write_text(html)

    with sync_playwright() as p:
        browser = p.chromium.launch()
        page = browser.new_page()
        page.goto(f"file://{tmp_path.resolve()}")
        page.wait_for_timeout(200)  # let web fonts settle
        page.pdf(
            path=str(out_path),
            format=page_format,
            print_background=True,
            margin={"top": "0", "bottom": "0", "left": "0", "right": "0"},
        )
        browser.close()

    tmp_path.unlink(missing_ok=True)
    print(f"Saved PDF: {out_path}")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Render a brand manual HTML file to PDF.")
    parser.add_argument("--html", required=True)
    parser.add_argument("--out", required=True)
    parser.add_argument("--format", default="Letter", help="Letter or A4")
    args = parser.parse_args()

    render_pdf(args.html, args.out, args.format)
