#!/usr/bin/env bash
# el-runtime-sources.sh — print the canonical El runtime link set.
#
# Reads lang/runtime/SOURCES (the single source of truth) and prints one path
# per line, optionally prefixed with a directory. Use it anywhere a link line
# would otherwise spell the runtime .c files out longhand:
#
#   cc -std=c11 -O2 -I lang/runtime -o app app.c \
#      $(scripts/el-runtime-sources.sh lang/runtime) \
#      -lcurl -lssl -lcrypto -lpthread -lm
#
# Options:
#   --headers   print the shipped headers instead of the .c sources
#   --check     verify every listed file exists; exit non-zero if any is missing
#
# WHY: linking el_runtime.c alone has been broken since el_runtime.c started
# calling into the engram siblings. The list was duplicated across ~8 build
# paths and drifted. It lives in exactly one place now — see lang/runtime/SOURCES.
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
SOURCES="${ROOT}/lang/runtime/SOURCES"

if [ ! -f "$SOURCES" ]; then
  echo "FATAL: canonical runtime source list missing: $SOURCES" >&2
  exit 1
fi

MODE="sources"
PREFIX=""
CHECK=0

for arg in "$@"; do
  case "$arg" in
    --headers) MODE="headers" ;;
    --check)   CHECK=1 ;;
    -*)        echo "el-runtime-sources.sh: unknown option: $arg" >&2; exit 2 ;;
    *)         PREFIX="${arg%/}/" ;;
  esac
done

# Strip comments and blank lines. Order is preserved — it is link order.
mapfile -t FILES < <(sed -e 's/#.*//' -e 's/[[:space:]]*$//' "$SOURCES" | grep -v '^$')

if [ "${#FILES[@]}" -eq 0 ]; then
  echo "FATAL: $SOURCES lists no sources" >&2
  exit 1
fi

if [ "$MODE" = "headers" ]; then
  # Every .c's matching .h, plus the headers that carry no .c of their own.
  HDRS=()
  for f in "${FILES[@]}"; do
    h="${f%.c}.h"
    [ -f "${ROOT}/lang/runtime/${h}" ] && HDRS+=("$h")
  done
  # Interface-only headers: no matching .c, but required to compile against.
  for h in eg_cosine_batch_strategy.h el_native_target.h el_platform_win.h; do
    [ -f "${ROOT}/lang/runtime/${h}" ] && HDRS+=("$h")
  done
  FILES=("${HDRS[@]}")
fi

RC=0
for f in "${FILES[@]}"; do
  if [ "$CHECK" -eq 1 ] && [ ! -f "${ROOT}/lang/runtime/${f}" ]; then
    echo "MISSING: lang/runtime/${f} (listed in lang/runtime/SOURCES)" >&2
    RC=1
  fi
  printf '%s%s\n' "$PREFIX" "$f"
done

exit $RC
