#!/usr/bin/env bash
# Checks the license data that the Koldflux font inspector shows against the google/fonts repository.
# 1. Fetches the google/fonts history without file contents (about 22 MB), unless a clone is given.
# 2. Opens the inspector for 10 families from /tools/fonts/youtube-thumbnails (every 20th in page order),
#    reads the license label and the pinned source link, clicks "Download license" and hashes the saved file.
# 3. Compares each saved file byte for byte with the license file in google/fonts at the pinned commit and at main,
#    checks METADATA.pb, checks all 196 families of the page by license folder, counts Reserved Font Names, runs controls.
# Usage: bash test-run.sh <work dir> [existing google/fonts clone]
# Needs: git, python3 3.9+, node with Playwright (PLAYWRIGHT_MODULE path is set inside check-inspector.cjs).
# Exit 0 only if every check passed.
set -u
here="$(cd "$(dirname "$0")" && pwd)"
work="${1:-}"; gf="${2:-}"
if [ -z "$work" ]; then echo "usage: bash test-run.sh workdir [google-fonts-clone]"; exit 2; fi
mkdir -p "$work/dl" || exit 1
if [ -z "$gf" ]; then
  gf="$work/gf"
  [ -d "$gf/.git" ] || git clone -q --filter=blob:none --no-checkout https://github.com/google/fonts.git "$gf" || exit 1
fi
[ -d "$gf/.git" ] || { echo "not a git clone: $gf"; exit 1; }
curl -sf https://koldflux.com/tools/fonts/youtube-thumbnails -o "$work/yt.html" || exit 1
# yt-index.json: slug, family and license of the page's 196 families, copied from the Koldflux font index on 2026-11-29.
[ -s "$here/yt-index.json" ] || { echo "missing yt-index.json next to this script"; exit 1; }
python3 -B - "$work/yt.html" "$work/yt-hrefs.json" "$work/sample10.json" <<'PY' || exit 1
import re, json, sys
h = open(sys.argv[1]).read(); seen = []; out = []
for m in re.finditer(r'href="(/tools/fonts/collection/[a-z0-9-]+\?font=([a-z0-9-]+)#editor)"', h):
    if m.group(2) not in seen: seen.append(m.group(2)); out.append([m.group(1), m.group(2)])
if not out: sys.exit("no families found on the page")
json.dump(out, open(sys.argv[2], "w")); json.dump(out[0:200:20], open(sys.argv[3], "w"))
print(len(out), "families on the page; sample:", [x[1] for x in out[0:200:20]])
PY
node "$here/check-inspector.cjs" "$work/sample10.json" "$work/inspector-10.json" "$work/dl" > "$work/inspector.log" || { tail -5 "$work/inspector.log"; exit 1; }
python3 -B "$here/check-licenses.py" "$work/inspector-10.json" "$work/yt-hrefs.json" "$here/yt-index.json" "$gf" "$work/dl"
r=$?
exit $r
