#!/usr/bin/env bash
# scripts/test: run pytest against a throwaway real Postgres (pgvector image).
#
#   scripts/test                 whole suite
#   scripts/test tests/test_x.py -k name -x     any pytest arguments
#
# Brings up pgvector/pgvector:pg17 on a random localhost port, runs pytest with
# RETICULA_TEST_DATABASE_URL pointing at it, removes the container afterwards.
# If RETICULA_TEST_DATABASE_URL is already set (CI service container, or your
# own Postgres with a superuser role) nothing is started. Works under stock
# macOS bash 3.2.
set -euo pipefail
cd "$(dirname "$0")/.."

if [ -n "${RETICULA_TEST_DATABASE_URL:-}" ]; then
    exec uv run pytest "$@"
fi

command -v docker >/dev/null 2>&1 || {
    echo "scripts/test: docker not found; set RETICULA_TEST_DATABASE_URL to a Postgres with pgvector instead" >&2
    exit 3
}

IMAGE="${RETICULA_TEST_IMAGE:-pgvector/pgvector:pg17}"
cid="$(docker run -d --rm \
    -e POSTGRES_HOST_AUTH_METHOD=trust \
    -p 127.0.0.1::5432 \
    "$IMAGE" \
    postgres -c fsync=off -c full_page_writes=off -c synchronous_commit=off -c max_connections=200)"
cleanup() { docker rm -f "$cid" >/dev/null 2>&1 || true; }
trap cleanup EXIT INT TERM

# Wait until the server accepts TCP connections (the image's init phase listens
# on the unix socket only, so test over 127.0.0.1 inside the container).
ready=""
for _ in $(seq 1 60); do
    if docker exec "$cid" psql -h 127.0.0.1 -U postgres -tAc 'select 1' >/dev/null 2>&1; then
        ready=1
        break
    fi
    sleep 1
done
[ -n "$ready" ] || { echo "scripts/test: postgres did not become ready" >&2; exit 4; }

port="$(docker port "$cid" 5432/tcp | head -n 1 | sed 's/.*://')"
export RETICULA_TEST_DATABASE_URL="postgresql://postgres@127.0.0.1:${port}/postgres"
uv run pytest "$@"
