"""The camera page in a browser, with a film standing in for the camera.

    python face/test_face_page.py [URL] [FOLDER]      -> "PASS <n> checks", exit 0

Without a URL the repository is served on a free local port; give https://6ense.com/ to check what is published.
With FOLDER, pictures of the page are saved there. Needs playwright with its Chromium, numpy and Pillow.

What stands in for the camera: a film made here, each time, from a photograph that is already on the site (the
keeper's own, people/alexander-vicol/avatar/photo.jpg). The face in it is still. Its skin, and only its skin (an
oval over the face; the background is left alone), is made a little brighter and darker at a known rate, in the
proportions blood gives the three colour channels, under sensor noise and a slow drift of the whole picture's
brightness. Chromium plays the film as its camera. So the check runs through everything the page does with a real
camera: the camera's stream, the face model finding the face, the skin patches, the colour trace, the pulse.

    a film pulsing 72 times a minute    the page must read 72, steadily
    a film pulsing 96 times a minute    the page must read 96: it follows the film, it does not guess a likely number
    the same film with no pulse in it   the page must never call anything steady, and never show a solid number

The film with no pulse is thirty seconds long where the others are ten. A film played round and round is itself a
rhythm: whatever its noise does, it does again every loop. The page looks at twelve seconds at a time, so a
thirty-second film never shows it the same stretch twice in one look, and what it sees is noise, as from a camera.
(The pulsing films may repeat: a pulse is meant to.)

It also checks what the page promises: that the camera is not touched until Start is pressed, that every request
the page makes is for one of this site's own files, that the browser refuses it a request to anywhere else, that
Stop lets go of the camera, that a refused camera is said in words, that the pulse is still read (from the middle
of the picture) when the face model cannot be loaded, and that the page stands with scripts off and on a phone.

What it cannot check: a person. A film of a still face has no movement, no changing light and no real blood in it.
"""
import functools
import http.server
import os
import shutil
import sys
import tempfile
import threading
import time
from urllib.parse import urlsplit

import numpy as np
from PIL import Image
from playwright.sync_api import sync_playwright

sys.dont_write_bytecode = True
if hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(encoding="utf-8", errors="replace")
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PHOTO = os.path.join(ROOT, "people", "alexander-vicol", "avatar", "photo.jpg")
ARGS = [a for a in sys.argv[1:] if not a.startswith("--")]
URL = ARGS[0] if ARGS else None
OUT = ARGS[1] if len(ARGS) > 1 else None
W, H, FPS, LOOP_S = 480, 360, 30, 10          # the film: ten seconds, played round and round
STILL_S = 30                                  # the film with no pulse: long enough that no 12-second look sees a stretch twice
passed, failed = 0, []


def check(ok, what, detail=""):
    global passed
    if ok:
        passed += 1
    else:
        failed.append(what)
        print("  FAIL %s %s" % (what, str(detail)[:400]))


# ------------------------------------------------------------------ the film
def make_film(path, bpm, depth=0.02, seed=7, seconds=LOOP_S):
    """A film of the photograph, the face's skin pulsing `bpm` times a minute. The loop holds a whole number of
    beats and of drift cycles, so it joins itself without a jump. depth=0 leaves the pulse out."""
    assert (bpm * seconds) % 60 == 0 and seconds % 5 == 0, "the loop must hold a whole number of beats and of drift cycles"
    photo = Image.open(PHOTO).convert("RGB").crop((112, 140, 912, 740)).resize((W, H), Image.LANCZOS)   # 4:3 round the face
    base = np.asarray(photo, dtype=np.float32)
    yy, xx = np.mgrid[0:H, 0:W].astype(np.float32)
    d = np.sqrt(((xx - 236) / 125) ** 2 + ((yy - 180) / 150) ** 2)          # 1 on the oval round the face
    skin = np.clip((1.12 - d) / 0.24, 0, 1)[..., None]                       # 1 inside, fading to 0 just outside it
    blood = np.array([0.33, 0.77, 0.53], dtype=np.float32)                   # how much each channel moves with a beat
    rng = np.random.default_rng(seed)
    with open(path, "wb") as f:
        f.write(b"YUV4MPEG2 W%d H%d F%d:1 Ip A1:1 C420jpeg\n" % (W, H, FPS))
        for i in range(FPS * seconds):
            t = i / FPS
            beat = np.sin(2 * np.pi * (bpm / 60) * t)
            drift = 1 + 0.01 * np.sin(2 * np.pi * 0.2 * t)                   # the room's light, breathing
            rgb = base * (1 + depth * beat * skin * blood) * drift + rng.normal(0, 1.5, base.shape).astype(np.float32)
            r, g, b = (np.clip(rgb[..., k], 0, 255) / 255 for k in range(3))
            y = 16 + 65.481 * r + 128.553 * g + 24.966 * b                   # BT.601, studio range
            u = 128 - 37.797 * r - 74.203 * g + 112.0 * b
            v = 128 + 112.0 * r - 93.786 * g - 18.214 * b
            half = lambda p: p.reshape(H // 2, 2, W // 2, 2).mean(axis=(1, 3))   # noqa: E731
            f.write(b"FRAME\n")
            for plane in (y, half(u), half(v)):
                f.write(np.clip(np.rint(plane), 0, 255).astype(np.uint8).tobytes())
    return path


# ------------------------------------------------------------------ a server for the folder
class Handler(http.server.SimpleHTTPRequestHandler):
    extensions_map = dict(http.server.SimpleHTTPRequestHandler.extensions_map,
                          **{".js": "text/javascript", ".mjs": "text/javascript", ".wasm": "application/wasm", ".task": "application/octet-stream"})

    def log_message(self, *a):
        pass


class Server(http.server.ThreadingHTTPServer):
    def handle_error(self, request, client_address):
        pass                                       # a browser that closes mid-download is not news


def serve():
    server = Server(("127.0.0.1", 0), functools.partial(Handler, directory=ROOT))
    threading.Thread(target=server.serve_forever, daemon=True).start()
    return server, "http://127.0.0.1:%d/" % server.server_address[1]


# ------------------------------------------------------------------ the page
STATE = "() => JSON.parse(JSON.stringify(window.__face.state))"
COUNT_ASKS = """() => { window.__asks = 0; const md = navigator.mediaDevices; if (!md) return;
  const real = md.getUserMedia.bind(md); md.getUserMedia = (c) => { window.__asks++; return real(c); }; }"""
INK = """(id) => { const c = document.getElementById(id), d = c.getContext('2d').getImageData(0, 0, c.width, c.height).data;
  let n = 0; for (let i = 3; i < d.length; i += 4) if (d[i] > 40) n++; return n; }"""


def launch(p, film=None, allow=True):
    args = ["--use-gl=angle", "--use-angle=swiftshader", "--enable-unsafe-swiftshader", "--use-fake-device-for-media-stream"]
    if film:
        args.append("--use-file-for-fake-video-capture=" + film)
    if allow:
        args.append("--use-fake-ui-for-media-stream")
    return p.chromium.launch(args=args)


# A test browser has nobody to say no, so the refusal is made the way a browser makes it: the request for the camera
# is turned down with the error a person's "Block" gives.
REFUSE = "() => { navigator.mediaDevices.getUserMedia = () => Promise.reject(new DOMException('Permission denied', 'NotAllowedError')); }"


def open_page(browser, site, path="face/", js=True, width=1280, height=900, block=(), refuse=False):
    origin = "{0.scheme}://{0.netloc}".format(urlsplit(site))
    ctx = browser.new_context(viewport={"width": width, "height": height}, java_script_enabled=js)
    pg = ctx.new_page()
    seen = {"errors": [], "requests": [], "outside": [], "console": []}
    pg.on("pageerror", lambda e: seen["errors"].append(str(e)[:200]))
    pg.on("console", lambda m: seen["console"].append(m.text[:200]) if m.type == "error" else None)

    def route(r):
        u = r.request.url
        if u.startswith(("data:", "blob:")):
            return r.continue_()
        seen["requests"].append(u)
        if not u.startswith(origin + "/"):
            seen["outside"].append(u)
            return r.abort()                       # nothing from this test leaves for another site, whatever the page tries
        if any(k in u for k in block):
            return r.abort()
        return r.continue_()

    pg.route("**/*", route)
    if js:
        pg.add_init_script("(" + (REFUSE if refuse else COUNT_ASKS) + ")()")
    pg.goto(site + path, wait_until="load")
    return pg, seen, origin


def watch(pg, seconds, every=0.5):
    """The page's state, sampled for a while."""
    rows = []
    end = time.time() + seconds
    while time.time() < end:
        rows.append(pg.evaluate(STATE))
        pg.wait_for_timeout(int(every * 1000))
    return rows


def film_run(p, site, tmp, bpm, first):
    film = make_film(os.path.join(tmp, "pulse_%d.y4m" % bpm), bpm)
    b = launch(p, film)
    pg, seen, origin = open_page(b, site)
    if first:
        print("1. before Start: the camera is not touched")
        check(pg.locator("h1").inner_text().startswith("Your pulse and your expression"), "the page says what it is")
        check(pg.locator("#start").is_enabled() and pg.locator("#stop").is_disabled() and pg.locator("#hint").is_visible(), "Start can be pressed, Stop cannot, and the stage says the camera is off")
        pg.wait_for_timeout(1500)
        st = pg.evaluate(STATE)
        check(pg.evaluate("() => window.__asks") == 0 and not st["running"] and st["model"] == "none", "nothing asked for the camera, and the face model was not loaded", st)
        check(not any("vendor/mediapipe" in u for u in seen["requests"]), "the 13 MB of face model are not fetched until Start is pressed")
        check(pg.locator("#bpm").inner_text().strip() == "–" and pg.locator("#pulse-state").inner_text().strip() == "not reading", "no number is shown for a pulse nobody has read")
        print("2. a film of a face pulsing %d times a minute stands in for the camera" % bpm)
    else:
        print("3. a film pulsing %d times a minute: the reading follows the film" % bpm)
    pg.locator("#start").click()
    try:
        pg.wait_for_function("() => ['GPU', 'CPU'].includes(window.__face.state.model)", timeout=90000)
    except Exception:
        pass
    st = pg.evaluate(STATE)
    check(st["model"] in ("GPU", "CPU") and st["running"], "the camera starts and the face model loads (%s)" % st["model"], (st, seen["errors"], seen["console"][:3]))
    try:
        pg.wait_for_function("() => window.__face.state.face && window.__face.state.samples > 30", timeout=30000)
    except Exception:
        pass
    st = pg.evaluate(STATE)
    check(st["face"] and st["samples"] > 30, "the model finds the face in the film, and skin colour is being read (%d pictures a second)" % st["fps"], st)
    if first:
        # before the rhythm has held for eight seconds: a number may show, but grey, and it is not called steady
        try:
            pg.wait_for_function("() => window.__face.state.bpm !== null", timeout=30000)
        except Exception:
            pass
        early = pg.evaluate("() => ({ s: JSON.parse(JSON.stringify(window.__face.state)), grey: document.getElementById('bpm').classList.contains('tentative'), words: document.getElementById('pulse-state').textContent })")
        check(early["s"]["bpm"] is not None and early["s"]["pulse"] == "reading" and early["grey"] and early["s"]["heldFor"] < 8 and early["s"]["rmssd"] is None,
              "the first number is shown grey, as a reading being made (%s), with no beat-to-beat variation yet" % early["words"], early)
    try:
        pg.wait_for_function("() => window.__face.state.pulse === 'steady' && window.__face.state.progress >= 99", timeout=60000)
    except Exception:
        pass
    rows = watch(pg, 8)
    read = [r["bpm"] for r in rows if r["bpm"] is not None]
    steady = sum(1 for r in rows if r["pulse"] == "steady")
    check(len(read) == len(rows) and max(abs(v - bpm) for v in read) <= 3,
          "the page reads %d a minute, within 3, for eight seconds running (read %s to %s)" % (bpm, min(read or [0]), max(read or [0])), rows[-1])
    check(steady == len(rows) and min(r["quality"] for r in rows) > 55, "and calls it steady throughout (signal quality %d to %d %%)" % (min(r["quality"] for r in rows), max(r["quality"] for r in rows)))
    shown = pg.locator("#bpm").inner_text().strip()
    solid = pg.evaluate("() => !document.getElementById('bpm').classList.contains('tentative') && !document.getElementById('bpm').classList.contains('held')")
    check(shown.isdigit() and abs(int(shown) - bpm) <= 3 and pg.locator("#pulse-state").inner_text().strip() == "steady" and solid and rows[-1]["heldFor"] >= 8,
          "the number on the page is that reading, solid now that the rhythm has held (%s)" % shown)
    if first:
        st = rows[-1]
        x = st["expression"]
        check(bool(x) and abs(sum(x["shares"].values()) - 1) < 0.02 and x["dominant"] in x["shares"], "an expression is named, and its seven shares sum to 100 %% (%s)" % (x and x["dominant"]), x)
        bars = pg.evaluate("() => [...document.querySelectorAll('#expr-bars li')].map((li) => [li.children[0].textContent, li.querySelector('[data-n]').textContent, li.classList.contains('lead')])")
        lead = [r[0] for r in bars if r[2]]
        check(len(bars) == 7 and lead == [x["dominant"]] and pg.locator("#expr-now").inner_text().startswith(x["dominant"]), "the bars show the seven shares and mark the one that leads", bars)
        check(st["ear"] is not None and 0.12 < st["ear"] < 0.6 and st["blinks"] == 0, "the eyes' opening is measured (%.2f), and a still face is not counted as blinking" % (st["ear"] or 0), st)
        check(st["rmssd"] is not None and st["rmssd"] <= 60, "beat-to-beat variation is given for this clean pulse, and it is small for a film that beats like a clock (RMSSD %s ms)" % st["rmssd"])
        check(pg.evaluate(INK, "wave") > 1500 and pg.evaluate(INK, "overlay") > 200, "the pulse wave is drawn, and the skin patches are outlined on the picture")
        box = pg.evaluate("""() => { const v = document.getElementById('cam').getBoundingClientRect(), s = document.getElementById('stage').getBoundingClientRect();
          return { same: Math.abs(v.width - s.width) < 2 && Math.abs(v.height - s.height) < 2, ratio: s.width / s.height }; }""")
        check(box["same"] and abs(box["ratio"] - W / H) < 0.05, "the stage takes the picture's own shape", box)
        if OUT:
            pg.screenshot(path=os.path.join(OUT, "face_reading.png"), full_page=True)
        print("   what the page promises about the camera's picture")
        check(pg.evaluate("() => window.__asks") == 1, "the camera was asked for once, by the press on Start")
        check(not seen["outside"] and all(u.startswith(origin + "/") for u in seen["requests"]),
              "every request the page made while reading was for one of this site's own files (%d requests)" % len(seen["requests"]), seen["outside"][:3])
        after = len(seen["requests"])
        refused = pg.evaluate("""async () => { let said = 0; document.addEventListener('securitypolicyviolation', () => said++);
          const tries = [() => fetch('https://example.org/take', { method: 'POST', body: 'x' }), () => new Promise((ok, no) => { const i = new Image(); i.onload = ok; i.onerror = no; i.src = 'https://example.org/p.gif?x=1'; }),
            () => new Promise((ok, no) => { const w = new WebSocket('wss://example.org/s'); w.onopen = ok; w.onerror = no; })];
          let stopped = 0; for (const t of tries) { try { await t(); } catch (e) { stopped++; } }
          return { stopped, said }; }""")
        check(refused["stopped"] == 3 and refused["said"] >= 3 and len(seen["requests"]) == after and not seen["outside"],
              "the browser refuses the page a request to another site (a post, a picture, a socket): none of the three left the page", (refused, seen["outside"]))
        print("   Stop")
        pg.locator("#stop").click()
        pg.wait_for_timeout(600)
        st = pg.evaluate(STATE)
        gone = pg.evaluate("() => document.getElementById('cam').srcObject === null")
        check(not st["running"] and gone and st["bpm"] is None and st["samples"] == 0, "Stop lets go of the camera and forgets the readings", st)
        check(pg.locator("#bpm").inner_text().strip() == "–" and "off" in pg.locator("#cam-status").inner_text() and pg.locator("#start").is_enabled() and pg.locator("#hint").is_visible(),
              "the page says the camera is off, shows no number, and can be started again")
        pg.locator("#start").click()
        pg.wait_for_function("() => window.__face.state.running && window.__face.state.samples > 10", timeout=30000)
        check(len([u for u in seen["requests"] if u.endswith("face_landmarker.task")]) == 1, "started again, it reads again without fetching the model a second time")
    check(not seen["errors"], "no script error", seen["errors"][:2])
    b.close()
    os.remove(film)


def main():
    server = None
    site = URL
    if site and not site.endswith("/"):
        site += "/"
    if not site:
        server, site = serve()
    if OUT:
        os.makedirs(OUT, exist_ok=True)
    tmp = tempfile.mkdtemp(prefix="face_film_")
    with sync_playwright() as p:
        film_run(p, site, tmp, 72, first=True)
        film_run(p, site, tmp, 96, first=False)

        print("4. the same film with no pulse in it: nothing is called steady")
        film = make_film(os.path.join(tmp, "still.y4m"), 72, depth=0.0, seconds=STILL_S)
        b = launch(p, film)
        pg, seen, _ = open_page(b, site)
        pg.locator("#start").click()
        pg.wait_for_function("() => window.__face.state.face && window.__face.state.progress >= 99", timeout=120000)
        solid = []
        rows = []
        end = time.time() + 30
        while time.time() < end:
            rows.append(pg.evaluate(STATE))
            solid.append(pg.evaluate("() => { const b = document.getElementById('bpm'); return /\\d/.test(b.textContent) && !b.classList.contains('tentative') && !b.classList.contains('held'); }"))
            pg.wait_for_timeout(400)
        states = sorted({r["pulse"] for r in rows})
        check("steady" not in states and not any(solid),
              "a face with no pulse in its colour is never called steady in thirty seconds, and no solid number is shown (states seen: %s; quality at most %d %%; longest hold %.1f s)"
              % (", ".join(states), max(r["quality"] for r in rows), max(r["heldFor"] for r in rows)), states)
        check(all(r["rmssd"] is None for r in rows) and all(r["arousal"] is None for r in rows), "and no beat-to-beat variation and no arousal index are made up for it")
        check(rows[-1]["face"] and rows[-1]["expression"] is not None, "while the face itself is still found and its expression read")
        if OUT:
            pg.screenshot(path=os.path.join(OUT, "face_no_pulse.png"), full_page=True)
        b.close()
        os.remove(film)                            # only once the browser that plays it has closed

        print("5. the face model does not arrive: the pulse is read from the middle of the picture, and the page says so")
        film = make_film(os.path.join(tmp, "pulse_72.y4m"), 72)
        b = launch(p, film)
        pg, seen, _ = open_page(b, site, block=("vendor/mediapipe/",))
        pg.locator("#start").click()
        pg.wait_for_function("() => window.__face.state.model === 'failed'", timeout=30000)
        check("could not be loaded" in pg.locator("#cam-status").inner_text() and "middle of the picture" in pg.locator("#cam-status").inner_text(), "the page says the model could not be loaded and where it reads instead")
        try:
            pg.wait_for_function("() => window.__face.state.pulse === 'steady' && window.__face.state.progress >= 99", timeout=60000)
        except Exception:
            pass
        rows = watch(pg, 5)
        read = [r["bpm"] for r in rows if r["bpm"] is not None]
        check(len(read) == len(rows) and max(abs(v - 72) for v in read) <= 3, "the pulse is still read: 72 a minute within 3 (read %s to %s)" % (min(read or [0]), max(read or [0])), rows[-1])
        check(rows[-1]["expression"] is None and "needs the face model" in pg.locator("#expr-now").inner_text() and pg.locator("#ear").inner_text().strip() == "–",
              "expression and eyes show nothing, and say that they need the model")
        check(not seen["errors"], "model gone: no script error", seen["errors"][:2])
        b.close()
        os.remove(film)

        print("6. the camera is refused")
        b = launch(p, None, allow=False)
        pg, seen, _ = open_page(b, site, refuse=True)
        pg.locator("#start").click()
        pg.wait_for_function("() => /not allowed|could not be opened|No camera/.test(document.getElementById('cam-status').textContent)", timeout=20000)
        st = pg.evaluate(STATE)
        check("not allowed" in pg.locator("#cam-status").inner_text() and not st["running"] and pg.locator("#start").is_enabled() and st["model"] == "none",
              "the page says the camera was not allowed, reads nothing, loads no model, and Start can be pressed again", (pg.locator("#cam-status").inner_text(), st))
        check(not seen["errors"], "camera refused: no script error", seen["errors"][:2])

        print("7. scripts off, and a phone")
        pg, seen, _ = open_page(b, site, js=False)
        check(pg.locator("#plain").is_visible() and pg.locator("#read").is_hidden() and pg.locator("#start").is_hidden(), "scripts off: a note says the camera part is left out, and no dead button is shown")
        check(pg.locator("table.face-how tbody tr").count() == 10 and "does not score lying" in pg.inner_text("#not") and "How this page is honest" in pg.inner_text("footer"),
              "scripts off: how each number is made, what the page does not do, and how it is honest are all there")
        named = pg.evaluate("() => [...document.querySelectorAll('table.face-how a, footer a, #how .status a')].map((a) => a.getAttribute('href')).filter((h) => !/^https?:/.test(h))")
        answers = [h for h in sorted(set(named)) if pg.context.request.get(site + "face/" + h).status != 200]
        check(len(set(named)) >= 10 and not answers, "every file the page names for a step or a check is there to open (%d files)" % len(set(named)), answers)
        pg, seen, _ = open_page(b, site, width=390, height=844)
        pg.wait_for_timeout(800)
        over = pg.evaluate("() => document.documentElement.scrollWidth - document.documentElement.clientWidth")
        check(over <= 0 and pg.locator("#start").is_visible(), "a phone: the page is as wide as the screen and Start is in reach", "%d px too wide" % over)
        if OUT:
            pg.screenshot(path=os.path.join(OUT, "face_phone.png"), full_page=True)
        pg, seen, _ = open_page(b, site, path="")
        check(pg.locator('nav a[href="face/"]').count() == 1 and pg.locator('#camera a.door[href="face/"]').count() == 1, "the home page opens this page from its menu and from a section of its own")
        b.close()
    shutil.rmtree(tmp, ignore_errors=True)         # the films are large: none is left behind
    if server:
        server.shutdown()
    print("PASS %d checks" % passed if not failed else "FAIL %d of %d: %s" % (len(failed), passed + len(failed), failed))
    sys.exit(1 if failed else 0)


if __name__ == "__main__":
    main()
