#!/usr/bin/env python3
"""The regression pass: screenshot targets, collect console errors, measure height.

    python scripts/regress.py OUTDIR '{"name":"#selector", ...}' [true]

Arg 3 `true` also takes a full-page screenshot and prints the page height.
The port comes from `SITE_PORTFILE` (default `/tmp/siteport.txt`), which is how
you point it at a second server — a mutation-test copy of the site, say.

The exit status is the point. Three lines come out, and they are three
different verdicts:

    ERRORS:    []   page errors and uncaught exceptions — the page is broken
    ASSERTS:   []   `console.assert` failures, i.e. an in-page fixture
                    disagreed with the page. These arrive as console messages
                    of type "assert", NOT "error", which is why they get their
                    own bucket and their own listener.
    WARNINGS:  []   console.warn noise; reported, not fatal

Exit 1 if ERRORS or ASSERTS is non-empty. **Every fixture assert you wrote is
checked here** — this one command is the whole test suite for a static
explainer.

Run it after every edit that touches app.js or data.js. Non-empty ERRORS means
the page is broken; do not commit.
"""
import asyncio, json, os, sys
from pathlib import Path
from playwright.async_api import async_playwright

PORTFILE = os.environ.get("SITE_PORTFILE", "/tmp/siteport.txt")


def port():
    return Path(os.environ.get("SITE_PORTFILE", PORTFILE)).read_text().strip()


async def main():
    out = sys.argv[1] if len(sys.argv) > 1 else "/tmp/shots"
    targets = json.loads(sys.argv[2]) if len(sys.argv) > 2 else {}
    full = json.loads(sys.argv[3]) if len(sys.argv) > 3 else "false"
    os.makedirs(out, exist_ok=True)

    async with async_playwright() as p:
        b = await p.chromium.launch()
        pg = await (await b.new_context(viewport={"width": 1440, "height": 1000})).new_page()
        # Three buckets, because the page uses all three and they mean
        # different things: an `assert` is a fixture that disagreed with the
        # page, an `error` is the page broken, a `warning` is noise you still
        # want to see. Lumping asserts in with errors hides which happened.
        errs, asserts, warns = [], [], []

        def on_console(m):
            if m.type == "assert":
                asserts.append(m.text)
            elif m.type == "error":
                errs.append(m.text)
            elif m.type == "warning":
                warns.append(m.text)

        pg.on("console", on_console)
        pg.on("pageerror", lambda e: errs.append("PAGEERROR " + str(e)))
        await pg.goto(f"http://127.0.0.1:{port()}/index.html")
        await pg.wait_for_timeout(1500)
        # smooth scrolling makes scroll_into_view land mid-animation; kill it.
        await pg.add_style_tag(content="html{scroll-behavior:auto!important}")

        for name, sel in targets.items():
            el = await pg.query_selector(sel)
            if el is None:
                print("MISSING", name, sel)
                errs.append(f"MISSING {name} {sel}")
                continue
            await el.scroll_into_view_if_needed()
            await pg.wait_for_timeout(1400)     # let d3 transitions finish
            await el.screenshot(path=f"{out}/{name}.png")
            print("shot", name, sel)

        if full:
            await pg.evaluate("window.scrollTo(0,0)")
            await pg.wait_for_timeout(600)
            await pg.screenshot(path=f"{out}/full.png", full_page=True)
            print("full height:", await pg.evaluate("document.body.scrollHeight"))

        print("ERRORS:", json.dumps(errs))
        print("ASSERTS:", json.dumps(asserts))
        print("WARNINGS:", json.dumps(warns))
        await b.close()
    sys.exit(1 if (errs or asserts) else 0)


asyncio.run(main())
