#!/usr/bin/env bash
# next/tests/http_content_type.sh — Step 8d-content-type test.
#
# Exercises content_type_for/1 and ok_response/2. 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/http_server.erl\")) :name)")

;; content_type_for returns the right byte size per format
(epoch 10)
(eval "(erlang-eval-ast \"byte_size(http_server:content_type_for(text))\")")
(epoch 11)
(eval "(erlang-eval-ast \"byte_size(http_server:content_type_for(json))\")")
(epoch 12)
(eval "(erlang-eval-ast \"byte_size(http_server:content_type_for(activity_json))\")")
(epoch 13)
(eval "(erlang-eval-ast \"byte_size(http_server:content_type_for(sx))\")")
(epoch 14)
(eval "(erlang-eval-ast \"byte_size(http_server:content_type_for(cbor))\")")

;; All content types are distinct
(epoch 15)
(eval "(get (erlang-eval-ast \"T = http_server:content_type_for(text), J = http_server:content_type_for(json), AJ = http_server:content_type_for(activity_json), S = http_server:content_type_for(sx), C = http_server:content_type_for(cbor), (T =/= J) and (J =/= AJ) and (AJ =/= S) and (S =/= C) and (T =/= C)\") :name)")

;; Unknown format -> text Content-Type
(epoch 16)
(eval "(get (erlang-eval-ast \"http_server:content_type_for(weird) =:= http_server:content_type_for(text)\") :name)")

;; ok_response/2 has shape [{status, 200}, {headers, [{ct, ...}]}, {body, ...}]
(epoch 17)
(eval "(get (erlang-eval-ast \"R = http_server:ok_response(<<1,2>>, json), case R of [{status, 200}, {headers, [{<<99,111,110,116,101,110,116,45,116,121,112,101>>, _}]}, {body, <<1,2>>}] -> ok; _ -> bad end\") :name)")

;; ok_response/2's CT value matches content_type_for for that format
(epoch 18)
(eval "(get (erlang-eval-ast \"R = http_server:ok_response(<<>>, sx), case R of [_, {headers, [{_, CT}]}, _] -> CT =:= http_server:content_type_for(sx); _ -> false end\") :name)")

;; ok_response/2 carries the body unchanged
(epoch 19)
(eval "(get (erlang-eval-ast \"R = http_server:ok_response(<<104,105>>, cbor), case R of [_, _, {body, <<104,105>>}] -> ok; _ -> bad end\") :name)")

;; activity_json starts with 'application' (97)
(epoch 20)
(eval "(get (erlang-eval-ast \"case http_server:content_type_for(activity_json) of <<97, _/binary>> -> ok; _ -> bad end\") :name)")

;; Existing ok_response/1 still works (backwards compat)
(epoch 21)
(eval "(get (erlang-eval-ast \"R = http_server:ok_response(<<1,2,3>>), case R of [{status, 200}, {headers, []}, {body, <<1,2,3>>}] -> ok; _ -> bad end\") :name)")
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  2  "module load name"                  "http_server"
check 10  "text -> 'text/plain' (10b)"        "10"
check 11  "json -> 'application/json' (16b)"  "16"
check 12  "activity_json (25b)"               "25"
check 13  "sx (14b)"                          "14"
check 14  "cbor (16b)"                        "16"
check 15  "all CTs distinct"                  "true"
check 16  "unknown -> text"                   "true"
check 17  "ok_response/2 shape"               "ok"
check 18  "ok_response/2 CT matches"          "true"
check 19  "body carried through"              "ok"
check 20  "activity_json starts 'a'"          "ok"
check 21  "ok_response/1 backward-compat"     "ok"

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