#!/usr/bin/env bash
# next/tests/registry_server.sh — Step 5b acceptance test.
#
# Exercises the gen_server-wrapped registry. Each test combines
# start_link + operations + assertion into a single
# erlang-eval-ast expression because the Erlang-on-SX scheduler
# does not preserve spawned processes across separate eval
# 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/registry.erl\")) :name)")

;; start_link returns a Pid
(epoch 10)
(eval "(get (erlang-eval-ast \"is_pid(registry:start_link())\") :name)")

;; register + lookup round-trip
(epoch 11)
(eval "(get (erlang-eval-ast \"registry:start_link(), registry:register(activity_types, create, e1), registry:lookup(activity_types, create) =:= {ok, e1}\") :name)")

;; lookup unknown name returns not_found
(epoch 12)
(eval "(get (erlang-eval-ast \"registry:start_link(), registry:lookup(activity_types, missing) =:= not_found\") :name)")

;; register returns the atom 'ok'
(epoch 13)
(eval "(get (erlang-eval-ast \"registry:start_link(), registry:register(object_types, note, e_n) =:= ok\") :name)")

;; list returns all pairs in a kind
(epoch 14)
(eval "(erlang-eval-ast \"registry:start_link(), registry:register(activity_types, a, 1), registry:register(activity_types, b, 2), registry:register(activity_types, c, 3), length(registry:list(activity_types))\")")

;; Re-register overrides without growing the list
(epoch 15)
(eval "(erlang-eval-ast \"registry:start_link(), registry:register(activity_types, a, v1), registry:register(activity_types, a, v2), length(registry:list(activity_types))\")")
(epoch 16)
(eval "(get (erlang-eval-ast \"registry:start_link(), registry:register(activity_types, a, v1), registry:register(activity_types, a, v2), registry:lookup(activity_types, a) =:= {ok, v2}\") :name)")

;; State persists across multiple calls in the same expression
(epoch 17)
(eval "(erlang-eval-ast \"registry:start_link(), registry:register(activity_types, x, 1), registry:register(object_types, x, 2), {registry:lookup(activity_types, x), registry:lookup(object_types, x)} =:= {{ok, 1}, {ok, 2}}\")")

;; Unknown kind rejected via gen_server too
(epoch 18)
(eval "(get (erlang-eval-ast \"registry:start_link(), case registry:lookup(bogus_kind, foo) of {error, unknown_kind} -> ok; _ -> bad end\") :name)")

;; Empty kind list returns []
(epoch 19)
(eval "(get (erlang-eval-ast \"registry:start_link(), registry:list(validators) =:= []\") :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  "gen_server loaded"                "gen_server"
check  3  "registry module loaded"           "registry"
check 10  "start_link returns Pid"           "true"
check 11  "register + lookup round-trip"     "true"
check 12  "lookup missing -> not_found"      "true"
check 13  "register returns ok atom"         "true"
check 14  "three registers, list = 3"        "3"
check 15  "re-register doesn't grow list"    "1"
check 16  "re-register overrides value"      "true"
check 17  "different kinds independent"      "true"
check 18  "lookup bogus kind"                "ok"
check 19  "empty kind list = []"             "true"

# 12 cases total (epoch 2 + 3 are setup, but counted for honesty)
TOTAL=$((PASS+FAIL))
if [ $FAIL -eq 0 ]; then
  echo "ok $PASS/$TOTAL next/tests/registry_server.sh passed"
else
  echo "FAIL $PASS/$TOTAL passed, $FAIL failed:"
  echo "$ERRORS"
fi
[ $FAIL -eq 0 ]
