"""The browser pass: uses the box through its own form the way a person on the
network would, photographs every surface at 1280x900 and 390x844 into shots/,
and measures what a screenshot cannot show (sideways scroll, radii, gradients,
dark mode, dialogs). Needs Go and Playwright for Python on the machine that runs
it; the box itself needs neither. From the project folder:

    uv run --with playwright python scripts/look.py

It waits for a real opening about two minutes ahead, so it takes about four.
"""

import os
import subprocess
import sys
import tempfile
import time
import urllib.request

from playwright.sync_api import sync_playwright

os.environ["TZ"] = "Europe/Berlin"
time.tzset()
SIZES = {"1280x900": (1280, 900), "390x844": (390, 844)}
WORK = tempfile.mkdtemp()
BIN = os.path.join(WORK, "opens-fridays")
problems: list[str] = []


def note(ok: bool, what: str) -> None:
    print(("ok    " if ok else "FAIL  ") + what)
    if not ok:
        problems.append(what)


def serve(port: int, opens: str, data: str) -> subprocess.Popen:
    log = open(os.path.join(WORK, f"{port}.log"), "a")
    p = subprocess.Popen([BIN, "-addr", f":{port}", "-data", data, "-opens", opens, "-window", "5m"], stdout=log, stderr=log)
    for _ in range(50):
        try:
            urllib.request.urlopen(f"http://127.0.0.1:{port}/")
            return p
        except OSError:
            time.sleep(0.1)
    sys.exit(f"server on {port} did not answer")


def halt(p: subprocess.Popen) -> None:
    p.terminate()
    p.wait()


def measure(page, label: str) -> None:
    """No sideways scroll at the viewport width, no radius, no gradient, no shadow."""
    m = page.evaluate(
        """() => {
        const all = [...document.querySelectorAll('*')];
        const cs = e => getComputedStyle(e);
        return {
            sw: document.documentElement.scrollWidth,
            vw: window.innerWidth,
            round: all.filter(e => ['borderTopLeftRadius','borderTopRightRadius','borderBottomLeftRadius','borderBottomRightRadius'].some(k => cs(e)[k] !== '0px')).map(e => e.tagName),
            grad: all.filter(e => cs(e).backgroundImage !== 'none').map(e => e.tagName),
            shadow: all.filter(e => cs(e).boxShadow !== 'none').map(e => e.tagName),
            bg: cs(document.body).backgroundColor,
        };
    }"""
    )
    note(m["sw"] <= m["vw"], f"{label}: no sideways scroll (scrollWidth {m['sw']}, viewport {m['vw']})")
    note(not m["round"] and not m["grad"] and not m["shadow"], f"{label}: no radius, gradient or shadow {m['round'] + m['grad'] + m['shadow']}")
    note(m["bg"] == "rgb(252, 240, 221)", f"{label}: cream ground ({m['bg']})")


def shoot(page, name: str, size: str, full: bool = False) -> None:
    page.screenshot(path=f"shots/{name}-{size}.png", full_page=full)


def put(page, port: int, text: str) -> None:
    page.goto(f"http://127.0.0.1:{port}/")
    page.fill("#note", text)
    page.click("text=Put it in")
    page.wait_for_load_state()


def main() -> None:
    subprocess.run(["go", "build", "-o", BIN, "."], check=True)
    os.makedirs("shots", exist_ok=True)
    now = time.time()
    opening = (int(now + 120) // 60 + 1) * 60
    opens = time.strftime("%a %H:%M", time.localtime(opening))
    hm = time.strftime("%H:%M", time.localtime(opening))
    data = os.path.join(WORK, "data")
    print(f"opening -opens '{opens}' (Europe/Berlin)")
    server = serve(8191, opens, data)
    base = "http://127.0.0.1:8191"
    dialogs: list[str] = []
    errors: list[str] = []
    with sync_playwright() as pw:
        browser = pw.chromium.launch()
        ctx = {s: browser.new_context(viewport={"width": w, "height": h}) for s, (w, h) in SIZES.items()}
        pages = {}
        for s, c in ctx.items():
            pages[s] = c.new_page()
            pages[s].on("dialog", lambda d: (dialogs.append(d.message), d.dismiss()))
            # The error pages answer 400 and 413 by design; Chromium logs those statuses.
            pages[s].on("console", lambda m: errors.append(m.text) if m.type == "error" and not any(f"status of {c}" in m.text for c in (400, 413)) else None)
            pages[s].on("pageerror", lambda e: errors.append(str(e)))

        for s, page in pages.items():
            page.goto(base + "/")
            shoot(page, "front-empty", s)
            measure(page, f"front {s}")
        # Notes typed into the form by the tester, one person at a time.
        typed = [
            "The meeting room on the second floor is booked all week by one calendar.",
            "Could the stand-up move to 10:00?\n\nNine is too early for the people who travel.",
            "<script>alert(1)</script>",
            "Éclairs on the last Friday of the month would be fine too.",
            "  more   plants near the windows  ",
        ]
        page = pages["1280x900"]
        put(page, 8191, typed[0])
        note(page.url.endswith("/received") and "Received. It will keep until" in page.content(), "a note goes in from the form and lands on Received")
        for s, p in pages.items():
            if s != "1280x900":
                put(p, 8191, typed[1])
            shoot(p, "received", s)
            measure(p, f"received {s}")
        for t in typed[2:]:
            put(page, 8191, t)

        for s, p in pages.items():
            p.goto(base + "/")
            p.fill("#note", "   \n   ")
            p.click("text=Put it in")
            note("Nothing was written. Nothing was put in." in p.content(), f"400 page {s}")
            shoot(p, "error-empty", s)
            # A browser keeps to maxlength; an older one would not. Remove it to reach the server's limit.
            p.goto(base + "/")
            p.evaluate("document.querySelector('#note').removeAttribute('maxlength')")
            long_text = "The printer jams.\n\n" + "It jams on every second page, " * 17
            p.fill("#note", long_text)
            p.click("text=Put it in")
            kept = p.input_value("#note")
            note(kept.replace("\r\n", "\n") == long_text, f"413 page keeps the text exactly as typed {s}")
            shoot(p, "error-too-long", s)
            measure(p, f"413 page {s}")
            p.goto(base + "/conditions")
            shoot(p, "conditions", s, full=True)
            measure(p, f"conditions {s}")
            p.goto(base + "/plate")
            shoot(p, "plate", s)
            measure(p, f"plate {s}")

        halt(server)  # a restart: the count is retaken with the minute of the start
        server = serve(8191, opens, data)
        for s, p in pages.items():
            p.goto(base + "/")
            note(f"{len(typed)} notes inside." in p.content(), f"front after a restart shows {len(typed)} notes inside. {s}")
            shoot(p, "front", s)
            measure(p, f"front {s}")

        dark = browser.new_context(viewport={"width": 1280, "height": 900}, color_scheme="dark").new_page()
        dark.goto(base + "/")
        shoot(dark, "front-os-dark", "1280x900")
        measure(dark, "front with the OS in dark mode")

        # The longest plate there is, at phone width.
        wed = serve(8192, "Wed 16:00", os.path.join(WORK, "wed"))
        p = pages["390x844"]
        p.goto("http://127.0.0.1:8192/")
        fits = p.evaluate("(() => { const e = document.querySelector('.plate'); return e.scrollWidth <= e.clientWidth && e.getBoundingClientRect().right <= innerWidth; })()")
        note(fits, "Opens Wednesdays 16:00 fits a 390 wide screen")
        shoot(p, "front-wednesday", "390x844")
        measure(p, "front, Wednesday plate, 390")
        p.goto("http://127.0.0.1:8192/plate")
        p.emulate_media(media="print")
        card = p.evaluate("(() => { const c = document.querySelector('.card').getBoundingClientRect(), e = document.querySelector('.card .plate').getBoundingClientRect(); return {gap: c.right - e.right, h: e.height}; })()")
        note(card["gap"] > 0 and card["h"] < 60, f"the A6 door card holds Opens Wednesdays 16:00 on one line ({card})")
        shoot(p, "plate-wednesday-print-media", "390x844")
        p.emulate_media(media="screen")
        halt(wed)

        print(f"waiting for the opening at {hm}")
        while time.time() < opening + 2:
            time.sleep(1)
        for s, p in pages.items():
            p.goto(base + "/")
            html = p.content()
            note("Suggestion box. Opened " in html and f"{len(typed)} notes." in html and f"Count shown on the page at opening: {len(typed)}." in html, f"opened sheet {s}")
            note("&lt;script&gt;alert(1)&lt;/script&gt;" in html, f"the script note is shown as text {s}")
            note(f"Count as of {hm}." in html and "0 notes inside." in html, f"new box restarts at 0, stamped {hm} {s}")
            shoot(p, "opened", s)
            shoot(p, "opened-full", s, full=True)
            measure(p, f"opened {s}")
            p.emulate_media(media="print")
            shoot(p, "opened-print-media", s, full=True)
            p.emulate_media(media="screen")
        browser.close()
    halt(server)
    note(not dialogs, f"no dialog opened {dialogs}")
    note(not errors, f"no console errors {errors}")
    print(f"look: {len(problems)} problems")
    sys.exit(1 if problems else 0)


if __name__ == "__main__":
    main()
