#!/usr/bin/env python3
"""Check every build at phone and tablet widths.

The desktop builds are posters: `1rem = 1% of 1536`. On a phone that silently
becomes a 25% scale, so the page "works" while its body copy is 6px. Nothing in
the desktop diff can see that, so this measures the things a phone cares about:

  median  the character-weighted median font size of text. Below ~13px the
          page has not been adapted; it is a shrunk poster.
  hscroll documentElement.scrollWidth vs clientWidth.
  taps    a rough tap-target count already accounted for in the text sizes.
  vh      page height in viewports. A hero that is 2.5 screens tall on a phone
          is usually a poster that failed to compress.

  python3 tools/mobile_qa.py --root ../..            # every build under builds/
  python3 tools/mobile_qa.py --root ../.. --widths 390,768
"""
import argparse
import glob
import os
import statistics


def probe(pg, url):
    pg.goto(url)
    try:
        pg.wait_for_function("document.fonts.status === 'loaded'", timeout=20000)
    except Exception:
        pass
    pg.wait_for_timeout(350)
    return pg.evaluate("""() => {
      const de = document.documentElement;
      const W = de.clientWidth;
      // leaf elements that carry words, so inherited wrappers do not skew it
      // weight each leaf by how many characters it actually renders: a page of
      // 11px uppercase labels over a 17px paragraph is adapted, a page of 6px
      // body copy is a shrunk poster, and an unweighted median confuses them
      const samples = [];
      document.querySelectorAll('body *').forEach(el => {
        if (el.children.length) return;
        const t = (el.textContent || '').trim();
        if (t.length < 2) return;
        const r = el.getBoundingClientRect();
        if (r.width <= 0 || r.height <= 0) return;
        samples.push([parseFloat(getComputedStyle(el).fontSize), t.length]);
      });
      samples.sort((a, b) => a[0] - b[0]);
      const totalChars = samples.reduce((n, s) => n + s[1], 0);
      let acc = 0, weighted = 0;
      for (const [fs, n] of samples) { acc += n; if (acc >= totalChars / 2) { weighted = fs; break; } }
      const sizes = samples.map(s => s[0]);
      // smallest tap target among interactive things
      let tap = 1e9;
      document.querySelectorAll('a, button').forEach(el => {
        const r = el.getBoundingClientRect();
        if (r.width > 0 && r.height > 0) tap = Math.min(tap, Math.min(r.width, r.height));
      });
      return {
        w: W,
        hscroll: de.scrollWidth - W,
        median: weighted,
        p75: sizes.length ? sizes[Math.floor(sizes.length * 0.75)] : 0,
        tiny: sizes.filter(s => s < 10).length,
        tap: tap === 1e9 ? null : Math.round(tap),
        vh: +(de.scrollHeight / window.innerHeight).toFixed(2),
      };
    }""")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--root", default=".")
    ap.add_argument("--widths", default="390,768")
    ap.add_argument("--height", type=int, default=844)
    a = ap.parse_args()

    widths = [int(w) for w in a.widths.split(",")]
    builds = sorted(glob.glob(os.path.join(a.root, "builds", "*/src/index.html")))
    if not builds:
        raise SystemExit(f"no builds under {a.root}")

    from playwright.sync_api import sync_playwright
    rows = []
    with sync_playwright() as p:
        b = p.chromium.launch()
        for path in builds:
            slug = os.path.basename(os.path.dirname(os.path.dirname(path)))
            url = "file://" + os.path.abspath(path)
            per = {}
            for w in widths:
                pg = b.new_page(viewport={"width": w, "height": a.height}, device_scale_factor=1)
                per[w] = probe(pg, url)
                pg.close()
            rows.append((slug, per))
        b.close()

    head = f"{'build':22s}" + "".join(f"{'@' + str(w):>18s}" for w in widths)
    print(head)
    print(f"{'':22s}" + "".join(f"{'median / scroll':>18s}" for w in widths))
    bad = []
    for slug, per in rows:
        line = f"{slug:22s}"
        for w in widths:
            r = per[w]
            flag = ""
            if r["hscroll"] > 1:
                flag += f" hs{r['hscroll']}"
            if r["median"] < 13:
                flag += " POSTER"
            line += f"{r['median']:7.1f} /{r['hscroll']:4d}{flag:<8s}"[:18]
            if flag:
                bad.append((slug, w, r, flag.strip()))
        print(line)

    print(f"\n{len(bad)} of {len(rows) * len(widths)} viewport checks need work")
    posters = sorted({s for s, _w, _r, f in bad if "POSTER" in f})
    if posters:
        print(f"not yet adapted (body text < 13px): {len(posters)}")
        print("  " + ", ".join(posters))


if __name__ == "__main__":
    main()
