#!/usr/bin/env bash
# Reproducible local test runner: build a Python 3.12 dev venv, install the pinned
# dev deps, and run the hermetic pytest suite. Matches what CI should run.
#
# Why 3.12 explicitly: the runtime deps pin versions that need 3.12, and a common box
# python (pyenv 3.10) ships without the `_sqlite3` extension, which the suite's
# conftest imports — so we don't just use whatever `python3` is on PATH.
#
#   ./scripts/test.sh            # full suite
#   ./scripts/test.sh tests/web  # pass pytest args through
set -euo pipefail
cd "$(dirname "$0")/.."

VENV="${VENV:-.venv-test}"

if [ ! -x "$VENV/bin/pytest" ]; then
  echo "==> Building dev venv ($VENV) on Python 3.12"
  if command -v uv >/dev/null 2>&1; then
    uv venv --python 3.12 "$VENV"
    VIRTUAL_ENV="$VENV" uv pip install -q -r requirements-dev.txt
  else
    PY="$(command -v python3.12 || echo "$HOME/.local/bin/python3.12")"
    "$PY" -c 'import sqlite3' 2>/dev/null || { echo "!! $PY lacks the sqlite3 module — install a 3.12 with sqlite (e.g. via uv)"; exit 1; }
    "$PY" -m venv "$VENV"
    "$VENV/bin/pip" install -q --upgrade pip
    "$VENV/bin/pip" install -q -r requirements-dev.txt
  fi
fi

echo "==> pytest ($("$VENV/bin/python" --version))"
exec "$VENV/bin/python" -m pytest "$@"
