#!/bin/sh
# SPDX-License-Identifier: AGPL-3.0-or-later

set -eu

SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
PROJECT_ROOT=$(dirname -- "$SCRIPT_DIR")

cd "$PROJECT_ROOT"

if [ -x "$PROJECT_ROOT/.venv/bin/python" ]; then
    PYTHON="$PROJECT_ROOT/.venv/bin/python"
elif command -v python3 >/dev/null 2>&1; then
    PYTHON=$(command -v python3)
else
    printf '%s\n' "error: python3 is required" >&2
    exit 127
fi

if ! "$PYTHON" -c 'import pytest' >/dev/null 2>&1; then
    printf '%s\n' "error: pytest is required; install requirements-dev.txt" >&2
    exit 127
fi

printf '%s\n' "Running test suite..."

# First argument may select a subset:
#   --fast             skip slow-marked end-to-end experiment tests
#   --fast --parallel  the same tests, spread over worker processes (takes no further arguments)
#   --slow             run only the slow-marked tests
MODE=""
PARALLEL=""
if [ "${1:-}" = "--fast" ]; then
    MODE="not slow"
    shift
    if [ "${1:-}" = "--parallel" ]; then
        PARALLEL=1
        shift
        if [ "$#" -ne 0 ]; then
            printf '%s\n' "error: --parallel takes no further arguments" >&2
            exit 2
        fi
    fi
elif [ "${1:-}" = "--slow" ]; then
    MODE="slow"
    shift
fi

# These modules scan the process table for leftover sandbox children and bound sandboxed runs at
# two wall-clock seconds, so another worker's processes make them fail. Measured: running them
# alongside the rest failed two or three of them on every run. They run alone, after the parallel
# phase, so the two phases together select exactly the tests `--fast` does.
SERIAL_MODULES="tests/test_batch3_execution.py tests/test_milestone3_sandbox.py tests/test_milestone3_acceptance.py"

if [ -n "$PARALLEL" ]; then
    if ! "$PYTHON" -c 'import xdist' >/dev/null 2>&1; then
        printf '%s\n' "check-tests: pytest-xdist is not installed; running serially (pip install -r requirements-dev.txt)" >&2
        exec "$PYTHON" -m pytest -m "$MODE" --durations=5
    fi
    WORKERS=$(nproc 2>/dev/null || echo 2)
    [ "$WORKERS" -gt 6 ] && WORKERS=6
    IGNORES=""
    for module in $SERIAL_MODULES; do
        IGNORES="$IGNORES --ignore=$module"
    done
    status=0
    # worksteal, not the default load: load hands the four heavy phase-2 tests to one worker.
    # shellcheck disable=SC2086
    "$PYTHON" -m pytest -m "$MODE" -n "$WORKERS" --dist worksteal --durations=5 $IGNORES || status=$?
    # shellcheck disable=SC2086
    "$PYTHON" -m pytest -m "$MODE" $SERIAL_MODULES --durations=5 || status=$?
    exit "$status"
fi

if [ -n "$MODE" ]; then
    exec "$PYTHON" -m pytest -m "$MODE" --durations=5 "$@"
fi
exec "$PYTHON" -m pytest "$@"
