#!/bin/bash
# Stress test for the HTTP server's arena memory management.
# Sends requests in rounds and reports memory stats per round.

set -e

PORT=9876

# Build
echo "building..."
zig build
SRC=examples/32-http-server.sx
cp "$SRC" "$SRC.bak"
sed "s/PORT :: 8080/PORT :: $PORT/" "$SRC.bak" > "$SRC"
./zig-out/bin/sx build examples/32-http-server.sx -o /tmp/sx-http-stress
mv "$SRC.bak" "$SRC"

# Start server
/tmp/sx-http-stress &
SERVER_PID=$!
sleep 0.3

if ! kill -0 $SERVER_PID 2>/dev/null; then
    echo "FAIL: server did not start"
    exit 1
fi

cleanup() {
    kill $SERVER_PID 2>/dev/null || true
    wait $SERVER_PID 2>/dev/null || true
    rm -f /tmp/sx-http-stress
}
trap cleanup EXIT

initial_rss=$(ps -o rss= -p $SERVER_PID | tr -d ' ')

run_round() {
    local count=$1
    local failures=0

    for i in $(seq 1 $count); do
        resp=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:$PORT 2>/dev/null) || true
        if [ "$resp" != "200" ]; then
            failures=$((failures + 1))
        fi
    done

    local rss=$(ps -o rss= -p $SERVER_PID | tr -d ' ')
    local delta=$((rss - initial_rss))
    printf "  %-8s requests  →  RSS: %s KB  (delta: %+d KB, %d failed)\n" "$count" "$rss" "$delta" "$failures"
}

echo ""
echo "initial RSS: ${initial_rss} KB"
echo ""

run_round 2000
run_round 3000
run_round 10000

final_rss=$(ps -o rss= -p $SERVER_PID | tr -d ' ')
total=$((2000 + 3000 + 10000))
echo ""
echo "--- summary ---"
echo "total requests: $total"
echo "initial RSS:    ${initial_rss} KB"
echo "final RSS:      ${final_rss} KB"
echo "total delta:    $((final_rss - initial_rss)) KB"
