#!/usr/bin/env bash
# Build the Remix frontend and package it for distribution.
#
# Environment variables:
#   OUTPUT_DIR  - where to write the tarball (default: ./dist)
#   VERSION     - version string (default: read from VERSION file)

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
WORKSPACE="${SCRIPT_DIR}/.."
OUTPUT_DIR="${OUTPUT_DIR:-${WORKSPACE}/dist}"
VERSION="${VERSION:-$(cat "${WORKSPACE}/VERSION" 2>/dev/null || echo "0.1.0")}"
FRONTEND_DIR="${WORKSPACE}/app/frontend"

echo "=== Dangerous Pi Frontend Build ==="
echo "Version: ${VERSION}"

cd "$FRONTEND_DIR"

# Install dependencies (including dev for build)
npm ci --production=false

# Build Remix app
npm run build

# Remove dev dependencies after build
npm prune --production

# Package
STAGING="/tmp/frontend-staging/frontend"
rm -rf /tmp/frontend-staging
mkdir -p "$STAGING"

cp -r build/ "$STAGING/"

cat > "${STAGING}/COMPONENT_VERSION" << EOF
{
  "component_id": "frontend",
  "version": "${VERSION}",
  "build_date": "$(date -u +"%Y-%m-%dT%H:%M:%SZ")"
}
EOF

mkdir -p "$OUTPUT_DIR"
TARBALL="frontend-${VERSION}.tar.gz"
cd /tmp/frontend-staging
tar -czf "${OUTPUT_DIR}/${TARBALL}" frontend/
echo "✅ Built: ${OUTPUT_DIR}/${TARBALL}"

rm -rf /tmp/frontend-staging
