#!/bin/sh
set -eu

ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
PORT=${ACE_HTTP_TEST_PORT:-18090}
LOG=${TMPDIR:-/tmp}/ace-http-integration.$$

cleanup() {
    if [ -n "${SERVER_PID:-}" ]; then
        pkill -TERM -P "$SERVER_PID" 2>/dev/null || true
        kill "$SERVER_PID" 2>/dev/null || true
        wait "$SERVER_PID" 2>/dev/null || true
    fi
    rm -f "$LOG"
}
trap cleanup EXIT INT TERM

export DYLD_LIBRARY_PATH="${DYLD_LIBRARY_PATH:-}"
export DYLD_FALLBACK_LIBRARY_PATH="${DYLD_FALLBACK_LIBRARY_PATH:-}"
source "$ROOT/scripts/env.sh"
# hello-api uses a fixed port; reject a conflicting listener rather than hiding it.
if curl -fsS "http://127.0.0.1:$PORT/ping" >/dev/null 2>&1; then
    echo "port $PORT is already in use" >&2
    exit 1
fi

cjpm build -m examples/hello-api >/dev/null
"$ROOT/target/release/bin/aceboot::hello_api" >"$LOG" 2>&1 &
SERVER_PID=$!

ready=0
i=0
while [ "$i" -lt 50 ]; do
    if curl -fsS "http://127.0.0.1:$PORT/ping" >/dev/null 2>&1; then ready=1; break; fi
    i=$((i + 1))
    sleep 0.1
done
[ "$ready" -eq 1 ] || { cat "$LOG" >&2; exit 1; }
sleep 0.1

[ "$(curl -fsS "http://127.0.0.1:$PORT/ping")" = "pong" ]
[ "$(curl -fsS "http://127.0.0.1:$PORT/hello/Cangjie")" = "Hello, Cangjie!" ]
[ "$(printf 'stream-upload' | curl --retry 3 --retry-all-errors -fsS --data-binary @- "http://127.0.0.1:$PORT/stream-size")" = "13" ]
status=$(dd if=/dev/zero bs=1025 count=1 2>/dev/null | curl --retry 3 --retry-all-errors -sS -o /dev/null -w '%{http_code}' --data-binary @- "http://127.0.0.1:$PORT/stream-size")
[ "$status" = "413" ]
[ "$(curl --retry 3 --retry-all-errors -fsS "http://127.0.0.1:$PORT/stream-response")" = "onetwo" ]
echo "HTTP request/response streaming integration passed"