#!/usr/bin/env bash
# Verify admin dist: chunks referenced in index.html must exist under deploy/admin/dist and be large enough
# (avoids nginx serving index.html for missing assets -> white screen, tiny JS/CSS in Network tab)
set -e
ROOT="${1:?usage: $0 <project-root>}"
D="$ROOT/deploy/admin/dist"
H="$D/index.html"
if [ ! -f "$H" ]; then
  echo "verify-admin-dist: missing $H" >&2
  exit 1
fi
if ! grep -qE '/admin/assets/[^"'\''<> ]+\.js' "$H"; then
  echo "verify-admin-dist: no /admin/assets/*.js in index.html (check admin/vite.config.js base: /admin/)" >&2
  exit 1
fi
TMP="$(mktemp)"
grep -oE '/admin/assets/[^"'\''<> ]+' "$H" | sort -u >"$TMP"
while IFS= read -r path; do
  [ -n "$path" ] || continue
  rel="${path#/admin}"
  f="$D$rel"
  if [ ! -f "$f" ]; then
    echo "verify-admin-dist: referenced but missing on disk: $path -> $f" >&2
    echo "  Deploy full deploy/admin/dist, not index.html alone." >&2
    rm -f "$TMP"
    exit 1
  fi
  sz=$(wc -c <"$f" 2>/dev/null | tr -d ' \r\n' || echo 0)
  if [ "${sz:-0}" -lt 800 ]; then
    echo "verify-admin-dist: file too small (${sz} bytes), likely wrong content: $f" >&2
    echo "  Admin build must mount repo root (see pull-and-restart.sh / restart.sh docker -v ROOT:/repo)." >&2
    rm -f "$TMP"
    exit 1
  fi
done <"$TMP"
rm -f "$TMP"

echo "verify-admin-dist: OK ($D)"
