#!/usr/bin/env bash
set -euo pipefail

SCRIPT="$(cd "$(dirname "$0")/../.." && pwd)/scripts/ci/wait-for-url.sh"
[ -x "$SCRIPT" ] || { echo "FAIL: $SCRIPT not executable"; exit 1; }

# Spin up a tiny HTTP server on a random free port.
PORT=$(python3 -c 'import socket; s=socket.socket(); s.bind(("",0)); print(s.getsockname()[1]); s.close()')
TMPDIR=$(mktemp -d)
echo "ok" > "$TMPDIR/index.html"
( cd "$TMPDIR" && python3 -m http.server "$PORT" >/dev/null 2>&1 ) &
SERVER_PID=$!
trap "kill $SERVER_PID 2>/dev/null; rm -rf $TMPDIR" EXIT

# Wait for server to come up
for _ in 1 2 3 4 5 6 7 8 9 10; do
  if curl -fsS "http://127.0.0.1:$PORT/" >/dev/null 2>&1; then break; fi
  sleep 0.2
done

# 200 case — should pass quickly
"$SCRIPT" "http://127.0.0.1:$PORT/" 5 1 || { echo "FAIL: expected 200 to succeed"; exit 1; }

# 404 case — script should fail (curl -f returns non-zero on 4xx)
if "$SCRIPT" "http://127.0.0.1:$PORT/no-such-path" 3 1 2>/dev/null; then
  echo "FAIL: expected 404 to fail"; exit 1
fi

# Network failure case — wrong port
if "$SCRIPT" "http://127.0.0.1:1/" 2 1 2>/dev/null; then
  echo "FAIL: expected unreachable URL to fail"; exit 1
fi

# Bad usage
if "$SCRIPT" 2>/dev/null; then
  echo "FAIL: expected usage error"; exit 1
fi

echo "PASS: wait-for-url.sh"
