#!/usr/bin/env bash
# next/tests/projection_server.sh — Step 7b acceptance test.
#
# Exercises gen_server-per-projection: start_link/3, async_fold/2,
# query/1. Each test inlines start_link with operations because
# the Erlang-on-SX scheduler doesn't preserve processes across
# separate erlang-eval-ast invocations. 10 cases.

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." >&2
  exit 1
fi

VERBOSE="${1:-}"
PASS=0; FAIL=0; ERRORS=""
TMPFILE=$(mktemp); trap "rm -f $TMPFILE" EXIT

cat > "$TMPFILE" <<'EPOCHS'
(epoch 1)
(load "lib/erlang/tokenizer.sx")
(load "lib/erlang/parser.sx")
(load "lib/erlang/parser-core.sx")
(load "lib/erlang/parser-expr.sx")
(load "lib/erlang/parser-module.sx")
(load "lib/erlang/transpile.sx")
(load "lib/erlang/runtime.sx")
(load "lib/erlang/vm/dispatcher.sx")
(epoch 2)
(eval "(er-load-gen-server!)")
(epoch 3)
(eval "(get (erlang-load-module (file-read \"next/kernel/projection.erl\")) :name)")

;; start_link returns a Pid registered under the given name
(epoch 10)
(eval "(get (erlang-eval-ast \"is_pid(projection:start_link(p1, 0, fun (_A, S) -> S + 1 end))\") :name)")

;; query before any async_fold returns initial state
(epoch 11)
(eval "(erlang-eval-ast \"projection:start_link(p1, 0, fun (_A, S) -> S + 1 end), projection:query(p1)\")")

;; Single async_fold + query returns new state
(epoch 12)
(eval "(erlang-eval-ast \"projection:start_link(p1, 0, fun (_A, S) -> S + 1 end), projection:async_fold(p1, a), projection:query(p1)\")")

;; Five async_folds accumulate
(epoch 13)
(eval "(erlang-eval-ast \"projection:start_link(p1, 0, fun (_A, S) -> S + 1 end), projection:async_fold(p1, 1), projection:async_fold(p1, 2), projection:async_fold(p1, 3), projection:async_fold(p1, 4), projection:async_fold(p1, 5), projection:query(p1)\")")

;; Custom initial state preserved
(epoch 14)
(eval "(erlang-eval-ast \"projection:start_link(p1, 42, fun (A, S) -> S + A end), projection:query(p1)\")")

;; Fold can read the activity (sum activities)
(epoch 15)
(eval "(erlang-eval-ast \"projection:start_link(p1, 0, fun (A, S) -> S + A end), projection:async_fold(p1, 10), projection:async_fold(p1, 20), projection:async_fold(p1, 30), projection:query(p1)\")")

;; List-append fold preserves insertion order (newest-first)
(epoch 16)
(eval "(get (erlang-eval-ast \"projection:start_link(p1, [], fun (A, S) -> [A | S] end), projection:async_fold(p1, a), projection:async_fold(p1, b), projection:async_fold(p1, c), projection:query(p1) =:= [c, b, a]\") :name)")

;; Two named projections are independent
(epoch 17)
(eval "(get (erlang-eval-ast \"projection:start_link(p1, 0, fun (_A, S) -> S + 1 end), projection:start_link(p2, [], fun (A, S) -> [A | S] end), projection:async_fold(p1, x), projection:async_fold(p1, y), projection:async_fold(p2, x), {projection:query(p1), projection:query(p2)} =:= {2, [x]}\") :name)")

;; Conditional fold (filter on activity tag)
(epoch 18)
(eval "(erlang-eval-ast \"projection:start_link(p1, 0, fun (A, S) -> case A of {keep, _} -> S + 1; _ -> S end end), projection:async_fold(p1, {keep, a}), projection:async_fold(p1, plain), projection:async_fold(p1, {keep, b}), projection:async_fold(p1, plain), projection:query(p1)\")")
EPOCHS

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

check() {
  local epoch="$1" desc="$2" expected="$3"
  local actual
  actual=$(echo "$OUTPUT" | awk -v e="$epoch" '
    $0 ~ "^\\(ok-len " e " " { getline; print; exit }
    $0 ~ "^\\(ok " e " "     { print; exit }
    $0 ~ "^\\(error " e " "  { print; exit }
  ')
  [ -z "$actual" ] && actual="<no output for epoch $epoch>"
  if echo "$actual" | grep -qF -- "$expected"; then
    PASS=$((PASS+1))
    [ "$VERBOSE" = "-v" ] && echo "  ok $desc"
  else
    FAIL=$((FAIL+1))
    ERRORS+="  FAIL [$desc] (epoch $epoch) expected: $expected | actual: $actual
"
  fi
}

check  2  "gen_server loaded"                "gen_server"
check  3  "projection module loaded"         "projection"
check 10  "start_link returns Pid"           "true"
check 11  "initial state via query"          "0"
check 12  "async_fold + query"               "1"
check 13  "five async_folds accumulate"      "5"
check 14  "custom initial state"             "42"
check 15  "fold reads activity (sum)"        "60"
check 16  "list-append fold order"           "true"
check 17  "two named projections indep."     "true"
check 18  "conditional fold (filter)"        "2"

TOTAL=$((PASS+FAIL))
if [ $FAIL -eq 0 ]; then
  echo "ok $PASS/$TOTAL next/tests/projection_server.sh passed"
else
  echo "FAIL $PASS/$TOTAL passed, $FAIL failed:"
  echo "$ERRORS"
fi
[ $FAIL -eq 0 ]
