#!/usr/bin/env bash
#
# build-stage.sh — Build the Stage marketing image (neuron-web + soul-demo).
#
# Thin wrapper around elb. The El build system handles compilation.
# ELB, ELC, and EL_RUNTIME must be set by the caller (extracted from ci-base
# in CI, or pointed at the local El SDK in dev).
#
# Usage:
#   ELB=/opt/el/dist/bin/elb ELC=... EL_RUNTIME=... ./build-stage.sh <tag>

set -euo pipefail
cd "$(dirname "$0")"

TAG="${1:-dev}"

if [ -z "${ELB:-}" ] || [ -z "${ELC:-}" ] || [ -z "${EL_RUNTIME:-}" ]; then
    echo "Error: ELB, ELC, and EL_RUNTIME must be set" >&2
    echo "  Extract from ci-base or point to local El SDK at foundation/el" >&2
    exit 1
fi

echo "==> Building neuron-web with elb"
"$ELB" build --elc "$ELC" --runtime "$EL_RUNTIME"
echo "    Binary: $(ls -lh dist/neuron-landing)"

echo "==> Compiling client-side El (src/js/*.el) → dist/js/"
cp "$EL_RUNTIME/el_runtime.js" src/js/
mkdir -p dist/js
for f in src/js/*.el; do
    [ -f "$f" ] || continue
    name=$(basename "$f" .el)
    "$ELC" --target=js --bundle --minify --obfuscate "$f" > "dist/js/${name}.js"
    echo "    compiled: src/js/${name}.el → dist/js/${name}.js"
done
rm -f src/js/el_runtime.js

echo "==> Building Docker image marketing:${TAG}"
docker build \
    --build-arg BUILDKIT_INLINE_CACHE=1 \
    --cache-from us-central1-docker.pkg.dev/neuron-785695/neuron-marketing/marketing:latest \
    -f Dockerfile.stage \
    -t "marketing:${TAG}" \
    .

# Extract soul-demo binary and engram snapshot from built image
echo "==> Packaging soul-demo:local image for k3s..."
CONTAINER_ID=$(docker create "marketing:${TAG}")
docker cp "${CONTAINER_ID}:/usr/local/bin/soul-demo" dist/soul-demo
docker cp "${CONTAINER_ID}:/srv/soul/engram-demo/snapshot.json" dist/soul-demo-snapshot.json 2>/dev/null || true
docker rm "${CONTAINER_ID}"

# Build minimal soul-demo container image
cp dist/soul-demo-snapshot.json dist/engram-snapshot.json 2>/dev/null || true
docker build \
  -f dist/Dockerfile.soul-demo \
  -t soul-demo:local \
  dist/

# Save as OCI tar for k3s to import at startup
docker save soul-demo:local -o dist/soul-demo-image.tar
echo "==> soul-demo:local image saved ($(du -sh dist/soul-demo-image.tar | cut -f1))"

echo "==> Done. marketing:${TAG} built."
