#!/usr/bin/env bash
# scripts/build_frontend.sh
# -------------------------
# Build the Vite SPA (frontend/v2/) and place the output in frontend/v2/dist/.
# Must be run before starting the FastAPI server.
#
# Usage:
#   bash scripts/build_frontend.sh
#   bash scripts/build_frontend.sh --clean   # wipe dist/ first

set -euo pipefail

cd "$(dirname "$0")/.."
ROOT=$(pwd)
FRONTEND="$ROOT/frontend/v2"

if [[ ! -d "$FRONTEND" ]]; then
    echo "[ERROR] Directory not found: $FRONTEND" >&2
    exit 1
fi

if [[ "${1:-}" == "--clean" ]]; then
    echo "[build] Cleaning dist/..."
    rm -rf "$FRONTEND/dist"
fi

echo "[build] Installing npm dependencies..."
cd "$FRONTEND"
npm ci --prefer-offline

echo "[build] Building Vite bundle..."
npm run build

DIST="$FRONTEND/dist"
if [[ ! -f "$DIST/index.html" ]]; then
    echo "[ERROR] Build failed — dist/index.html not found." >&2
    exit 1
fi

echo "[build] Done → $DIST"
echo "[build] Assets:"
du -sh "$DIST"
