#!/usr/bin/env bash
# next/tests/projection_pure.sh — Step 7a acceptance test.
#
# Exercises the pure-functional projection driver:
#   new/2,3, fold_activity/2, replay/2, name/1, state/1, fold_fn/1.
# Fold bodies are Erlang funs in v1; SX-source eval bridge will
# plug into the same record later. 12 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 "(get (erlang-load-module (file-read \"next/kernel/projection.erl\")) :name)")

;; new/2 sets initial state to the supplied value
(epoch 10)
(eval "(get (erlang-eval-ast \"P = projection:new(activity_log, init_state), projection:state(P) =:= init_state\") :name)")

;; new/2 default fold is identity
(epoch 11)
(eval "(get (erlang-eval-ast \"P = projection:new(activity_log, base), P1 = projection:fold_activity(P, anything), projection:state(P1) =:= base\") :name)")

;; new/3 stores supplied fold
(epoch 12)
(eval "(get (erlang-eval-ast \"P = projection:new(counter, 0, fun (_A, S) -> S + 1 end), is_function(projection:fold_fn(P))\") :name)")

;; fold_activity threads through the fold fn
(epoch 13)
(eval "(erlang-eval-ast \"P = projection:new(counter, 0, fun (_A, S) -> S + 1 end), P1 = projection:fold_activity(P, x), projection:state(P1)\")")

;; Two fold_activity calls accumulate
(epoch 14)
(eval "(erlang-eval-ast \"P = projection:new(counter, 0, fun (_A, S) -> S + 1 end), P1 = projection:fold_activity(P, a), P2 = projection:fold_activity(P1, b), projection:state(P2)\")")

;; replay over a list
(epoch 15)
(eval "(erlang-eval-ast \"P = projection:new(counter, 0, fun (_A, S) -> S + 1 end), P1 = projection:replay(P, [a, b, c, d, e]), projection:state(P1)\")")

;; replay over [] returns the projection unchanged (state preserved)
(epoch 16)
(eval "(erlang-eval-ast \"P = projection:new(counter, 99, fun (_A, S) -> S + 1 end), P1 = projection:replay(P, []), projection:state(P1)\")")

;; Fold can read activity content (here append it)
(epoch 17)
(eval "(get (erlang-eval-ast \"P = projection:new(byname, [], fun (A, S) -> [A | S] end), P1 = projection:replay(P, [a, b, c]), projection:state(P1) =:= [c, b, a]\") :name)")

;; Different projections are independent (different fold bodies)
(epoch 18)
(eval "(get (erlang-eval-ast \"P1 = projection:new(p_count, 0, fun (_A, S) -> S + 1 end), P2 = projection:new(p_collect, [], fun (A, S) -> [A | S] end), R1 = projection:replay(P1, [a, b, c]), R2 = projection:replay(P2, [a, b, c]), {projection:state(R1), projection:state(R2)} =:= {3, [c, b, a]}\") :name)")

;; Name accessor
(epoch 19)
(eval "(get (erlang-eval-ast \"projection:name(projection:new(some_name, init)) =:= some_name\") :name)")

;; Multi-step replay: aggregator by activity tag
(epoch 20)
(eval "(get (erlang-eval-ast \"By = fun (A, S) -> case A of {tag, T} -> [T | S]; _ -> S end end, P = projection:new(tag_log, [], By), P1 = projection:replay(P, [{tag, foo}, plain, {tag, bar}, {tag, baz}]), projection:state(P1) =:= [baz, bar, foo]\") :name)")
EPOCHS

OUTPUT=$(timeout 120 "$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  "module load name"                  "projection"
check 10  "new/2 stores initial state"        "true"
check 11  "default fold is identity"          "true"
check 12  "new/3 stores fold fn"              "true"
check 13  "fold_activity threads fn"          "1"
check 14  "two folds accumulate"              "2"
check 15  "replay over 5 activities"          "5"
check 16  "replay over [] preserves state"    "99"
check 17  "fold can read activity content"    "true"
check 18  "different projections indep."      "true"
check 19  "name accessor"                     "true"
check 20  "tag-aware fold (replay)"           "true"

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