#!/usr/bin/env bash
# next/tests/http_listen_bif.sh — Step 8a acceptance test.
#
# Verifies the http:listen/2 BIF wrapper is registered and
# validates its arguments. We do NOT exercise the actual listen
# loop — http-listen blocks forever, so production callers spawn
# an Erlang process to host the call. The BIF wrapper itself is
# tested for: registration, integer port enforcement, function
# handler enforcement.
#
# This BIF is the briefing's allowed-exception scope addition
# to lib/erlang/runtime.sx. 5 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")

;; BIF registered under http/listen/2
(epoch 10)
(eval "(not (= (er-lookup-bif \"http\" \"listen\" 2) nil))")

;; BIF is non-pure (side effect: opens a socket)
(epoch 11)
(eval "(get (er-lookup-bif \"http\" \"listen\" 2) :pure?)")

;; Non-integer port -> badarg
(epoch 12)
(eval "(get (erlang-eval-ast \"try http:listen(not_a_number, fun () -> ok end) catch error:badarg -> ok end\") :name)")

;; Non-fun handler -> badarg
(epoch 13)
(eval "(get (erlang-eval-ast \"try http:listen(8080, not_a_fun) catch error:badarg -> ok end\") :name)")

;; Wrong arity not registered (http/listen/1 should be nil)
(epoch 14)
(eval "(= (er-lookup-bif \"http\" \"listen\" 1) nil)")
EPOCHS

OUTPUT=$(timeout 60 "$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 10  "BIF registered under http/listen/2" "true"
check 11  "BIF marked non-pure"                "false"
check 12  "non-integer port -> badarg"         "ok"
check 13  "non-fun handler -> badarg"          "ok"
check 14  "no /1 arity registered"             "true"

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