#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT_DIR"

fail() {
  echo "[userfront-loading-policy] $*" >&2
  exit 1
}

if rg -n "FontLoader|assets/fonts/NotoSansKR|_loadBundledFonts" userfront/lib userfront/pubspec.yaml; then
  fail "userfront must not block first render on bundled NotoSansKR font loading"
fi

if rg -n "dotenv\.load|touch \.env" userfront/lib/main.dart userfront/Dockerfile; then
  fail "userfront web startup must not request or create public .env assets"
fi

if rg -n "fontFamily:\s*['\"]NotoSansKR['\"]" userfront/lib; then
  fail "userfront theme must use the platform default font"
fi

if rg -n "await ThemeController\.(app|auth)\.restore" userfront/lib/main.dart; then
  fail "theme restore must not block the first render"
fi

if rg -n "fonts\.googleapis\.com/icon\?family=Material\+Icons" userfront/web/index.html; then
  fail "userfront must not load Google Material Icons stylesheet on the login critical path"
fi

if rg -n -- "--no-tree-shake-icons" userfront/Dockerfile userfront-e2e/package.json; then
  fail "userfront web release build must allow icon tree shaking"
fi

rg -q "optimize-web-build\.mjs" userfront/Dockerfile || fail "Docker build must hash and pre-compress Flutter web entrypoints"
rg -q "nginx-mod-http-brotli" userfront/Dockerfile || fail "runtime image must install the nginx Brotli module"
rg -Fq "main\\.dart\\.[0-9a-f]{12}" userfront/nginx.conf || fail "hashed app entrypoints must use immutable cache"
rg -q "brotli_static\s+on;" userfront/nginx.conf || fail "nginx must serve pre-compressed brotli assets"
rg -q "brotliCompressSync" userfront/scripts/optimize-web-build.mjs || fail "Docker build optimization must generate brotli assets"
rg -q "modulepreload" userfront/scripts/optimize-web-build.mjs || fail "Docker build optimization must preload wasm module entrypoints"
rg -q "canvasKitBaseUrl:\"canvaskit/\"" userfront/scripts/optimize-web-build.mjs || fail "userfront web build must force local CanvasKit instead of fetching engine resources from a CDN"
rg -q "_flutter\.loader\.load\(\{config:\{canvasKitBaseUrl:\"canvaskit/\"\}\}\);" userfront/scripts/optimize-web-build.mjs || fail "Flutter service worker registration must be removed from cold path"
if rg -n "gzip|gzipSync|\\.gz" userfront/nginx.conf userfront/scripts/optimize-web-build.mjs; then
  fail "userfront web compression must be managed as brotli-only"
fi
rg -q "Cache-Control.*no-cache" userfront/nginx.conf || fail "HTML/app shell must use no-cache revalidation"
rg -q "Cache-Control.*immutable" userfront/nginx.conf || fail "versioned static assets must use immutable cache"
