#!/usr/bin/env python3
"""Full-page screenshots of every app page in one language, for visual review.

    venv/bin/python scripts/i18n-shots.py de                 # all pages
    venv/bin/python scripts/i18n-shots.py de /settings /admin # only these
    venv/bin/python scripts/i18n-shots.py de --mobile         # 390px viewport

Writes PNGs to screenshots_to_review/i18n-<lang>/. Reads the page list and the
per-language account from i18n-verify.py, so the two stay in sync.

What to look for that no automated check catches: text overflowing its button
or pill, a nav label wrapping to two lines, a table header cut off, a sentence
that is grammatical but reads like a machine wrote it. German and Polish run
30-40% longer than English, so truncation is the expected failure here.
"""
import asyncio
import json
import os
import sys

# i18n-verify.py is not an importable module name, so read its constants out
# of the source instead of duplicating the host and the account table here.
_here = os.path.dirname(os.path.abspath(__file__))
_ns = {}
exec(compile(open(os.path.join(_here, "i18n-verify.py")).read(),
             "i18n-verify.py", "exec"), _ns)
BASE = _ns["BASE"]
account_for = _ns["account_for"]

from playwright.async_api import async_playwright


async def main():
    if len(sys.argv) < 2:
        raise SystemExit("usage: i18n-shots.py <lang> [path-filter ...] [--mobile]")
    lang = sys.argv[1]
    mobile = "--mobile" in sys.argv
    filters = [a for a in sys.argv[2:] if not a.startswith("--")]

    with open(os.path.join(_here, "i18n-pages.json")) as fh:
        pages = json.load(fh)
    if filters:
        pages = [p for p in pages if any(f in p for f in filters)]

    out = os.path.join(os.path.dirname(_here), "screenshots_to_review",
                       f"i18n-{lang}" + ("-mobile" if mobile else ""))
    os.makedirs(out, exist_ok=True)
    email, password = account_for(lang)

    async with async_playwright() as pw:
        browser = await pw.chromium.launch()
        ctx = await browser.new_context(
            ignore_https_errors=True,
            viewport={"width": 390, "height": 844} if mobile
            else {"width": 1440, "height": 900},
        )
        page = await ctx.new_page()
        await page.goto(f"{BASE}/login", wait_until="domcontentloaded")
        await page.fill('input[name="username"]', email)
        await page.fill('input[name="password"]', password)
        await page.click('button[type="submit"], input[type="submit"]')
        await page.wait_for_load_state("networkidle")
        if "/login" in page.url:
            raise SystemExit(f"login failed for {email}")
        await page.goto(f"{BASE}/lang/{lang}", wait_until="domcontentloaded")

        for path in pages:
            name = path.strip("/").replace("/", "_").replace("?", "-") or "index"
            resp = await page.goto(BASE + path, wait_until="networkidle")
            status = resp.status if resp else "?"
            shot = os.path.join(out, f"{name}.png")
            await page.screenshot(path=shot, full_page=True)
            print(f"{path:36} {status}  {shot}")

        await browser.close()


asyncio.run(main())
