#!/usr/bin/env bash
# Build the Command Center: frontend first, then embed and Go-build.
#
# Output: ./command-center (Linux: ELF; macOS: Mach-O; Windows: PE)
#
# Environment variables:
#   GOOS, GOARCH        — cross-compile target (default: host)
#   COMMAND_CENTER_TAG  — Go build tag (default: empty). Use `no_duckdb` to
#                          produce a CGO-free build for hosts without a C
#                          compiler. Production builds MUST omit this tag.
set -euo pipefail

cd "$(dirname "$0")/.."
ROOT=$(pwd)

VERSION=$(git rev-parse --short HEAD 2>/dev/null || echo dev)

echo "==> Building frontend (web/)"
pushd web >/dev/null
if [ ! -d node_modules ]; then
  npm ci
fi
npm run build
popd >/dev/null

echo "==> Staging frontend bundle into internal/webui/dist/"
rm -rf internal/webui/dist
mkdir -p internal/webui/dist
cp -R web/dist/. internal/webui/dist/
# Re-create the .gitkeep so a clean checkout still passes `go test ./...`.
touch internal/webui/dist/.gitkeep

echo "==> Building Go binary"
LDFLAGS="-s -w -X main.version=${VERSION}"
BUILD_TAGS="${COMMAND_CENTER_TAG:-}"

if [ -n "$BUILD_TAGS" ]; then
  echo "    build tags: $BUILD_TAGS"
  go build -tags "$BUILD_TAGS" -ldflags "$LDFLAGS" -o command-center ./cmd/command-center
else
  go build -ldflags "$LDFLAGS" -o command-center ./cmd/command-center
fi

echo "==> Done: $ROOT/command-center ($(wc -c < command-center) bytes)"
