#!/bin/bash
# build_vindex_bench.sh — build the vindex_bench oracle/proof harness, with
# the real ggml + hand-rolled-Metal batch-cosine strategies on Darwin and a
# zero-dependency CPU-only stub everywhere else. Mirrors the two-step recipe
# documented in vindex_bench.c's own header comment; this script exists so
# that recipe is one command, not a copy-pasted paragraph.
#
# Darwin build links FOUR strategy translation units:
#   eg_cosine_batch.c                    — the Factory (always)
#   eg_cosine_batch_strategy_cpu.c       — universal fallback (always)
#   eg_cosine_batch_strategy_ggml.c      — ggml + dynamic Metal backend plugin
#   eg_cosine_batch_strategy_metal_hand.m — PR #114's original hand-rolled
#                                            Metal shader, preserved as one
#                                            selectable strategy
# plus -DEG_HAVE_STRATEGY_GGML -DEG_HAVE_STRATEGY_METAL_HAND so the Factory
# (and vindex_bench.c's own direct strategy comparison) knows both exist.
#
# ggml is resolved via `brew --prefix ggml` when available (portable across
# Intel /usr/local and Apple Silicon /opt/homebrew installs), falling back to
# /opt/homebrew if brew isn't on PATH. Override with GGML_PREFIX=... env var.
#
# Usage: ./build_vindex_bench.sh [output_path]
set -euo pipefail
cd "$(dirname "$0")"
OUT="${1:-./vindex_bench}"
CC="${CC:-cc}"

if [ "$(uname -s)" = "Darwin" ]; then
  GGML_PREFIX="${GGML_PREFIX:-$(brew --prefix ggml 2>/dev/null || echo /opt/homebrew)}"
  echo "== Darwin: building with the ggml + hand-rolled-Metal strategies (ggml prefix: $GGML_PREFIX) =="

  "$CC" -O2 -std=c11 -x objective-c \
    -c eg_cosine_batch_strategy_metal_hand.m -o /tmp/eg_cosine_batch_strategy_metal_hand.o \
    -framework Metal -framework Foundation

  "$CC" -O2 -std=c11 -DEG_HAVE_STRATEGY_GGML -DEG_HAVE_STRATEGY_METAL_HAND -w \
    -I"$GGML_PREFIX/include" \
    vindex_bench.c engram_vindex.c \
    eg_cosine_batch.c eg_cosine_batch_strategy_cpu.c eg_cosine_batch_strategy_ggml.c \
    /tmp/eg_cosine_batch_strategy_metal_hand.o \
    -L"$GGML_PREFIX/lib" -lggml -lggml-base \
    -Wl,-rpath,"$GGML_PREFIX/lib" \
    -lm -framework Metal -framework Foundation -o "$OUT"
else
  echo "== non-Darwin: building with the CPU-only fallback strategy (no ggml, no Metal) =="
  "$CC" -O2 -std=c11 -w vindex_bench.c engram_vindex.c \
    eg_cosine_batch.c eg_cosine_batch_strategy_cpu.c \
    -lm -o "$OUT"
fi

echo "built: $OUT"
