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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
TEST_PORT=39217

fail() {
  printf 'FAIL: %s\n' "$1" >&2
  exit 1
}

cleanup() {
  if [[ -n "${LISTENER_PID:-}" ]]; then
    kill "${LISTENER_PID}" 2>/dev/null || true
    wait "${LISTENER_PID}" 2>/dev/null || true
  fi
}
trap cleanup EXIT

if ! python3 -c "import socket; s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM); s.close()" 2>/dev/null; then
  printf 'SKIP: IPv6 sockets unavailable in this environment\n'
  exit 0
fi

# IPv6-only listener on ::1 (invisible to IPv4-only probes)
python3 -c "
import socket
import time

s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
s.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
s.bind(('::1', ${TEST_PORT}))
s.listen(1)
while True:
    time.sleep(3600)
" &
LISTENER_PID=$!

# Give the listener time to bind
sleep 0.2

# Verify IPv4 probe does not see the listener (sanity check for the test setup)
if nc -z 127.0.0.1 "${TEST_PORT}" 2>/dev/null; then
  fail "test setup error: IPv4 probe unexpectedly sees port ${TEST_PORT}"
fi

# Verify IPv6 probe does see the listener
if ! nc -z ::1 "${TEST_PORT}" 2>/dev/null; then
  fail "test setup error: IPv6 probe cannot see port ${TEST_PORT}"
fi

# shellcheck source=bin/ensure-web.sh
source "${ROOT_DIR}/bin/ensure-web.sh"

result="$(HARNESS_WEB_PORT="${TEST_PORT}" find_free_port)"
if [[ "${result}" -le "${TEST_PORT}" ]]; then
  fail "find_free_port should return port > ${TEST_PORT} when ::1 listener is bound (got ${result})"
fi

printf 'PASS: find_free_port skipped IPv6-only listener on port %s, returned %s\n' "${TEST_PORT}" "${result}"
