#!/usr/bin/env bash
# build.sh — build the El organ.
#
# El has no import system on this path, so the modules are concatenated in
# dependency order (the same thing elp/tests/run.sh does) and handed to elc as
# one unit. The two device realizers are then linked in.
#
# MUST be run from the repo root, or the .psv phoneme geometry will not resolve
# and the render silently degrades.
set -uo pipefail

OUT="${1:-./peripheral/organ}"
REPO="$(cd "$(dirname "$0")/.." && pwd)"
cd "$REPO"

WORK="$(mktemp -d)"
trap 'rm -rf "$WORK"' EXIT

# Dependency order. The elp modules supply the render (synth_codes) and the
# phoneme-geometry read; the organ supplies everything else.
cat elp/src/voice-profile.el \
    elp/src/accent.el \
    elp/src/voice-ingest.el \
    elp/src/speech-ingest.el \
    elp/src/speech.el \
    peripheral/src/organ.el \
    peripheral/src/organ_dsp.el \
    peripheral/src/organ_converse.el \
    peripheral/src/organ_cli.el \
  | grep -v '^import ' > "$WORK/organ.el"

cd "$REPO/lang"
./dist/platform/elc "$WORK/organ.el" > "$WORK/organ.c" || { echo "elc failed" >&2; exit 1; }

SSL_PREFIX="$(brew --prefix openssl@3 2>/dev/null || echo /usr/local)"

# The peripheral realizers are per-platform: Darwin gets the real devices,
# anything else gets el_peripheral_null.c and honestly reports having none.
case "$(uname)" in
  Darwin)
    # The Objective-C realizers are compiled SEPARATELY, with -fobjc-arc. The
    # capture realizer is written against ARC (it holds AVFoundation objects);
    # compiling it MRR silently changes its memory semantics, which on a device
    # path shows up as a use-after-free under load rather than as an error here.
    cc -std=c11 -fobjc-arc -O1 -I runtime -c runtime/el_audio_darwin.m   -o "$WORK/el_audio.o"   || exit 1
    cc -std=c11 -fobjc-arc -O1 -I runtime -c runtime/el_capture_darwin.m -o "$WORK/el_capture.o" || exit 1
    PERIPH_SRC="$WORK/el_audio.o $WORK/el_capture.o"
    PERIPH_LIBS="-framework AudioToolbox -framework AVFoundation -framework CoreMedia
                 -framework CoreVideo -framework CoreGraphics -framework ImageIO
                 -framework Foundation"
    ;;
  *)
    PERIPH_SRC="runtime/el_peripheral_null.c"
    PERIPH_LIBS=""
    ;;
esac

cc -O1 -I runtime -I"$SSL_PREFIX/include" -L"$SSL_PREFIX/lib" \
   -o "$OUT" "$WORK/organ.c" \
   runtime/el_runtime.c runtime/el_seed.c \
   runtime/engram_cognition.c runtime/engram_geometry.c runtime/engram_reason.c \
   runtime/engram_store.c runtime/engram_verify.c runtime/engram_vindex.c \
   runtime/eg_cosine_batch.c runtime/eg_cosine_batch_strategy_cpu.c \
   $PERIPH_SRC $PERIPH_LIBS \
   -lcurl -lssl -lcrypto -lpthread -lm || { echo "link failed" >&2; exit 1; }

echo "built: $OUT"
