#!/usr/bin/env bash
# build.sh — compile an El program that uses the swarm capability.
#
# Concatenates the El native-concurrency stdlib (thread.el, channel.el) and the
# swarm capability modules in dependency order, then the user program, compiles
# with the canonical elc, and links against the shared C runtime.
#
# Usage:
#   swarm/build.sh <program.el> <out-binary>
#
# The swarm modules use only el_runtime.c builtins plus thread.el/channel.el,
# so nothing else needs concatenating (engram_*, json_*, str_*, fs_*, http_*,
# uuid_v4, now_millis are all C builtins in el_runtime.c).

set -uo pipefail
cd "$(dirname "$0")/.."          # -> lang/
LANG_DIR="$(pwd)"
ELC="${ELC:-${LANG_DIR}/dist/platform/elc}"
RT="${LANG_DIR}/el-compiler/runtime"

PROG="${1:?usage: build.sh <program.el> <out-binary>}"
OUT="${2:?usage: build.sh <program.el> <out-binary>}"

# swarm module load order (each may depend on those before it):
#   worktrack   — durable work-tracking journal (no swarm deps)
#   containment — the three containment rules (no swarm deps)
#   primitives  — think/act/attend/intend/learn seam (no swarm deps)
#   ccr         — per-worker compiled bounded context (depends: primitives)
#   swarm       — orchestrator: fan-out/converge (depends: all above + thread)
SWARM_MODULES="
  swarm/worktrack.el
  swarm/containment.el
  swarm/primitives.el
  swarm/reshape_surface.el
  swarm/primitive_binding.el
  swarm/primitive_seam.el
  swarm/ccr.el
  swarm/swarm.el
"

TMP_C="$(mktemp -t swarm_build.XXXXXX).c"
COMBINED="$(mktemp -t swarm_combined.XXXXXX).el"

cat runtime/thread.el runtime/channel.el $SWARM_MODULES "$PROG" > "$COMBINED"

if ! "$ELC" "$COMBINED" > "$TMP_C" 2>/tmp/swarm.elc.err; then
    echo "elc FAILED:" >&2
    sed 's/^/    /' /tmp/swarm.elc.err >&2
    rm -f "$TMP_C" "$COMBINED"
    exit 1
fi

if ! cc -O2 -DHAVE_CURL -I "$RT" "$TMP_C" "$RT/el_runtime.c" -lcurl -lpthread -lm -o "$OUT" 2>/tmp/swarm.cc.err; then
    echo "cc FAILED:" >&2
    sed 's/^/    /' /tmp/swarm.cc.err >&2
    rm -f "$TMP_C" "$COMBINED"
    exit 1
fi

rm -f "$TMP_C" "$COMBINED"
echo "built: $OUT"
