#!/usr/bin/env bash
# Runs inside the pinned Playwright Linux image (docker/visual/docker-compose.yml).
# docs/specs/007-simulator-based-testing.md phase 3.
set -euo pipefail

# Linux-native install. Skip it when the cached node_modules volume already has
# this lockfile's deps (incl. the free-icon font); a stale volume is cleared with
# `docker compose -f docker/visual/docker-compose.yml down -v`.
if [ ! -x node_modules/.bin/vite ] || [ ! -d node_modules/@fortawesome/fontawesome-free ]; then
  echo "visual: installing linux dependencies (npm ci)…"
  npm ci --no-audit --no-fund
fi

# Provision icons from Font Awesome *Free* (a redistributable devDependency), not
# the licensed Pro webfonts which cannot ship to CI or to developer desktops.
#
# This is the app's supported free-tier recipe, unchanged: drop in only
# fa-solid-900, which fills the "Font Awesome 6 Free" @font-face (base/_fonts.scss)
# that the icon font stack falls back to (fontawesome/_core.scss). Because no Pro
# webfont (fa-light-300/fa-regular-400) is present, hasProIcon() is false and the
# runtime Pro→Free icon remapping (src/mixins/icon.ts) is exercised — so the suite
# baselines exactly what a free deployment renders, and covers that fallback path.
FREE="node_modules/@fortawesome/fontawesome-free/webfonts"
DST="public/configurator/fonts/fontawesome6"
mkdir -p "$DST"
cp "$FREE/fa-solid-900.woff2" "$FREE/fa-solid-900.ttf" "$DST/"
echo "visual: provisioned Font Awesome Free (fa-solid-900)"

# The dev server (started by Playwright's webServer) proxies /api here.
export VITE_API_PROXY="http://sim:8080"

# Wait for the simulator to answer before handing off to Playwright, so the first
# test does not race the container's boot (FM-5).
echo "visual: waiting for the simulator…"
until curl -sf http://sim:8080/api/pub/version >/dev/null 2>&1; do
  sleep 0.5
done
echo "visual: simulator is up"

# shellcheck disable=SC2086
exec npx playwright test -c playwright.visual.config.ts ${PW_ARGS:-}
