"""Print the two guides to PDF, one file per guide per language.

    python infra/guides/make_pdf.py              # all four
    python infra/guides/make_pdf.py learner-ar   # one

The guide is one HTML file carrying both languages, with the one to show chosen by `data-lang` on the root —
so each PDF is the same file printed twice, with that attribute set and the other language's half left hidden
by the stylesheet. The print rules the page already has (no site header, no language switcher, no call to
action, no picture broken across a page) are the ones that apply.

Two things have to be done before the shutter that a browser would do on its own only when you scroll: every
picture is `loading="lazy"` and would print as a blank box, and the Arabic face comes from Google Fonts, so
both are waited for. The pages are A4 with the margins of something meant to be read on paper and a page
number in the footer, in the language being printed.
"""
import pathlib
import sys

from playwright.sync_api import sync_playwright

SRC = pathlib.Path(__file__).resolve().parents[2] / "apps/cms/public/guides"
JOBS = {
    "learner-ar": ("learner.html", "ar", "دليل الطالب · Thinkera", "صفحة"),
    "learner-en": ("learner.html", "en", "Thinkera · The student guide", "Page"),
    "trainer-ar": ("trainer.html", "ar", "دليل المدرب · Thinkera", "صفحة"),
    "trainer-en": ("trainer.html", "en", "Thinkera · The instructor guide", "Page"),
}

FOOT = """
<div style="width:100%; font-family: 'IBM Plex Sans Arabic', sans-serif; font-size:8pt; color:#6b7a90;
            padding:0 14mm; display:flex; justify-content:space-between; direction:{dir};">
  <span>{title}</span>
  <span>{word} <span class="pageNumber"></span> / <span class="totalPages"></span></span>
</div>"""

HEAD = '<div style="font-size:1pt; color:transparent;">.</div>'


def build(page, name, source, lang, title, word):
    page.goto((SRC / source).as_uri(), wait_until="networkidle")
    page.evaluate("""lang => {
        document.documentElement.setAttribute('data-lang', lang);
        document.documentElement.setAttribute('lang', lang === 'en' ? 'en' : 'ar');
        document.documentElement.setAttribute('dir', lang === 'en' ? 'ltr' : 'rtl');
        // the pictures carry one accessible name per language, as the switcher swaps them
        document.querySelectorAll('img[data-alt-en]').forEach(img => {
            const alt = img.getAttribute('data-alt-' + lang);
            if (alt) { img.setAttribute('alt', alt); }
        });
        // nothing scrolls while printing, so a lazy picture would never be asked for
        document.querySelectorAll('img[loading="lazy"]').forEach(img => { img.loading = 'eager'; });
    }""", lang)
    page.wait_for_function(
        "() => Array.from(document.images).every(i => i.complete && i.naturalWidth > 0)", timeout=60000)
    page.evaluate("document.fonts.ready")
    page.wait_for_timeout(1200)
    out = SRC / (name + ".pdf")
    page.pdf(path=str(out), format="A4", print_background=True,
             display_header_footer=True, header_template=HEAD,
             footer_template=FOOT.format(dir="rtl" if lang == "ar" else "ltr", title=title, word=word),
             margin={"top": "14mm", "bottom": "16mm", "left": "12mm", "right": "12mm"})
    print(f"  {out.name}  {out.stat().st_size // 1024} kB")


wanted = [a for a in sys.argv[1:] if not a.startswith("-")] or list(JOBS)
with sync_playwright() as pw:
    browser = pw.chromium.launch(channel="chrome")
    context = browser.new_context(viewport={"width": 1100, "height": 1400})
    page = context.new_page()
    for name in wanted:
        build(page, name, *JOBS[name])
    browser.close()
print("done")
