#!/usr/bin/env bash
# El pre-commit hook: compile and run native tests before commit.
# Install once per clone: git config core.hooksPath .githooks

set -euo pipefail

ROOT="$(git rev-parse --show-toplevel)"
LANG_DIR="$ROOT/lang"
RUNTIME="$LANG_DIR/el-compiler/runtime"
ELC="$LANG_DIR/dist/platform/elc"

# If elc isn't built yet, skip with a warning rather than blocking
if [ ! -x "$ELC" ]; then
  echo "⚠  elc not found at lang/dist/platform/elc — skipping pre-commit tests"
  echo "   Build it first: cd lang && gcc -O2 -I el-compiler/runtime dist/elc-bootstrap.c el-compiler/runtime/el_runtime.c -lcurl -lpthread -o dist/elc-gen2 && ./dist/elc-gen2 el-compiler/src/compiler.el > /tmp/elc.c && gcc -O2 -I el-compiler/runtime /tmp/elc.c el-compiler/runtime/el_runtime.c -lcurl -lpthread -o dist/platform/elc"
  exit 0
fi

echo "→ Running El native tests..."
PASS=0
FAIL=0
FAILED_TESTS=""

for test_file in "$LANG_DIR"/tests/native/test_*.el; do
  name=$(basename "$test_file" .el)
  tmp_c="/tmp/el_hook_${name}.c"
  tmp_bin="/tmp/el_hook_${name}"

  if "$ELC" --test "$test_file" > "$tmp_c" 2>/dev/null \
     && gcc -O2 -I "$RUNTIME" "$tmp_c" "$RUNTIME/el_runtime.c" \
          -lcurl -lpthread -lm -o "$tmp_bin" 2>/dev/null \
     && "$tmp_bin" 2>/dev/null; then
    PASS=$((PASS + 1))
  else
    echo "  ✗ $name"
    FAIL=$((FAIL + 1))
    FAILED_TESTS="$FAILED_TESTS $name"
  fi
done

echo "  $PASS passed, $FAIL failed"

if [ "$FAIL" -gt 0 ]; then
  echo ""
  echo "✗ Pre-commit failed. Fix these tests before committing:$FAILED_TESTS"
  exit 1
fi

echo "✓ All tests passed"
exit 0
