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

PROJECT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
cd "$PROJECT_DIR"

SKIP_INSTALL=0
SKIP_PYTHON=0

for arg in "$@"; do
  case "$arg" in
    --skip-install)
      SKIP_INSTALL=1
      ;;
    --skip-python)
      SKIP_PYTHON=1
      ;;
    *)
      echo "Unknown option: $arg" >&2
      echo "Usage: ./scripts/build-all.sh [--skip-install] [--skip-python]" >&2
      exit 1
      ;;
  esac
done

if [ "$SKIP_INSTALL" -eq 0 ]; then
  echo "[1/5] Installing backend dependencies"
  npm ci

  echo "[2/5] Installing UI dependencies"
  npm --prefix ui ci
else
  echo "[1/5] Skipping dependency installation"
  echo "[2/5] Reusing existing node_modules"
fi

echo "[3/5] Building backend"
npm run build:server

echo "[4/5] Building UI"
npm --prefix ui run build

if [ "$SKIP_PYTHON" -eq 0 ]; then
  echo "[5/5] Pre-baking Python packages for the Bash sandbox"
  # Non-fatal: the script warns and exits 0 if pip/python is unavailable, so a
  # missing python toolchain never breaks the JS build. Skip with --skip-python.
  bash "$PROJECT_DIR/scripts/prebake-python.sh" || true
else
  echo "[5/5] Skipping Python pre-bake (--skip-python)"
fi

echo "Build complete: backend dist/ and ui/dist/ are ready"
