#!/usr/bin/env bash
# lib/forth/test.sh — smoke-test the Forth runtime layer.

set -uo pipefail
cd "$(git rev-parse --show-toplevel)"

SX_SERVER="${SX_SERVER:-hosts/ocaml/_build/default/bin/sx_server.exe}"
if [ ! -x "$SX_SERVER" ]; then
  SX_SERVER="/root/rose-ash/hosts/ocaml/_build/default/bin/sx_server.exe"
fi
if [ ! -x "$SX_SERVER" ]; then
  echo "ERROR: sx_server.exe not found."
  exit 1
fi

TMPFILE=$(mktemp); trap "rm -f $TMPFILE" EXIT

cat > "$TMPFILE" << 'EPOCHS'
(epoch 1)
(load "lib/forth/runtime.sx")
(epoch 2)
(load "lib/forth/tests/runtime.sx")
(epoch 3)
(eval "(list forth-test-pass forth-test-fail)")
EPOCHS

OUTPUT=$(timeout 60 "$SX_SERVER" < "$TMPFILE" 2>/dev/null)

LINE=$(echo "$OUTPUT" | awk '/^\(ok-len 3 / {getline; print; exit}')
if [ -z "$LINE" ]; then
  LINE=$(echo "$OUTPUT" | grep -E '^\(ok 3 \([0-9]+ [0-9]+\)\)' | tail -1 \
          | sed -E 's/^\(ok 3 //; s/\)$//')
fi
if [ -z "$LINE" ]; then
  echo "ERROR: could not extract summary"
  echo "$OUTPUT" | tail -20
  exit 1
fi

P=$(echo "$LINE" | sed -E 's/^\(([0-9]+) ([0-9]+)\).*/\1/')
F=$(echo "$LINE" | sed -E 's/^\(([0-9]+) ([0-9]+)\).*/\2/')
TOTAL=$((P + F))

if [ "$F" -eq 0 ]; then
  echo "ok $P/$TOTAL lib/forth tests passed"
else
  echo "FAIL $P/$TOTAL passed, $F failed"
  TMPFILE2=$(mktemp)
  cat > "$TMPFILE2" << 'EPOCHS2'
(epoch 1)
(load "lib/forth/runtime.sx")
(epoch 2)
(load "lib/forth/tests/runtime.sx")
(epoch 3)
(eval "(map (fn (f) (list (get f :name) (get f :got) (get f :expected))) forth-test-fails)")
EPOCHS2
  FAILS=$(timeout 60 "$SX_SERVER" < "$TMPFILE2" 2>/dev/null | grep -E '^\(ok-len 3' -A1 | tail -1 || true)
  echo "  Details: $FAILS"
  rm -f "$TMPFILE2"
fi

[ "$F" -eq 0 ]
