#!/usr/bin/env bash
# next/tests/registry_pure.sh — Step 5a acceptance test.
#
# Exercises the pure-functional registry API: new/0, kinds/0,
# register/4, lookup/3, list/2. State threading is verified
# by chaining register calls and inspecting the final state.
# 13 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/registry.erl\")) :name)")

;; new/0 returns []
(epoch 10)
(eval "(get (erlang-eval-ast \"registry:new() =:= []\") :name)")

;; kinds/0 has 7 entries
(epoch 11)
(eval "(erlang-eval-ast \"length(registry:kinds())\")")

;; kinds/0 includes activity_types
(epoch 12)
(eval "(get (erlang-eval-ast \"lists:member(activity_types, registry:kinds())\") :name)")

;; register + lookup round-trip
(epoch 13)
(eval "(get (erlang-eval-ast \"{ok, S} = registry:register(activity_types, create, [{cid, c1}], registry:new()), registry:lookup(activity_types, create, S) =:= {ok, [{cid, c1}]}\") :name)")

;; lookup on empty registry returns not_found
(epoch 14)
(eval "(get (erlang-eval-ast \"registry:lookup(activity_types, anything, registry:new()) =:= not_found\") :name)")

;; lookup on unknown kind returns {error, unknown_kind}
(epoch 15)
(eval "(get (erlang-eval-ast \"case registry:lookup(bogus_kind, foo, registry:new()) of {error, unknown_kind} -> ok; _ -> bad end\") :name)")

;; register on unknown kind returns {error, unknown_kind}
(epoch 16)
(eval "(get (erlang-eval-ast \"case registry:register(bogus_kind, foo, bar, registry:new()) of {error, unknown_kind} -> ok; _ -> bad end\") :name)")

;; list of empty kind returns []
(epoch 17)
(eval "(get (erlang-eval-ast \"registry:list(activity_types, registry:new()) =:= []\") :name)")

;; Three registers + list returns 3 pairs
(epoch 18)
(eval "(erlang-eval-ast \"{ok, S1} = registry:register(activity_types, create, e1, registry:new()), {ok, S2} = registry:register(activity_types, update, e2, S1), {ok, S3} = registry:register(activity_types, delete, e3, S2), length(registry:list(activity_types, S3))\")")

;; Re-registering same name overrides previous entry
(epoch 19)
(eval "(get (erlang-eval-ast \"{ok, S1} = registry:register(activity_types, create, v1, registry:new()), {ok, S2} = registry:register(activity_types, create, v2, S1), registry:lookup(activity_types, create, S2) =:= {ok, v2}\") :name)")

;; Re-registering same name keeps list length at 1
(epoch 20)
(eval "(erlang-eval-ast \"{ok, S1} = registry:register(activity_types, create, v1, registry:new()), {ok, S2} = registry:register(activity_types, create, v2, S1), length(registry:list(activity_types, S2))\")")

;; Different kinds are independent
(epoch 21)
(eval "(erlang-eval-ast \"{ok, S1} = registry:register(activity_types, x, 1, registry:new()), {ok, S2} = registry:register(object_types, x, 2, S1), {registry:lookup(activity_types, x, S2), registry:lookup(object_types, x, S2)} =:= {{ok, 1}, {ok, 2}}\")")

;; list on unknown kind returns {error, unknown_kind}
(epoch 22)
(eval "(get (erlang-eval-ast \"case registry:list(bogus_kind, registry:new()) of {error, unknown_kind} -> ok; _ -> bad end\") :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"                    "registry"
check 10  "new/0 returns []"                    "true"
check 11  "kinds/0 length"                      "7"
check 12  "kinds/0 includes activity_types"     "true"
check 13  "register + lookup round-trip"        "true"
check 14  "lookup empty -> not_found"           "true"
check 15  "lookup bogus kind"                   "ok"
check 16  "register bogus kind"                 "ok"
check 17  "list empty kind -> []"               "true"
check 18  "three registers, list returns 3"     "3"
check 19  "re-register overrides entry"         "true"
check 20  "re-register doesn't grow list"       "1"
check 21  "different kinds independent"         "true"
check 22  "list bogus kind"                     "ok"

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