#!/bin/bash

set -e # Exit immediately if a command exits with a non-zero status.
set -u # Treat unset variables as an error when substituting.
set -o pipefail # The return value of a pipeline is the status of the last command to exit with a non-zero status.

# --- Configuration ---
# Name for a shared virtual environment for development tools (like tox, mypy, flake8)
VENV_DIR_TOOLS=".venv_dev_tools"
# Python interpreter to use for the tools virtual environment
PYTHON_INTERPRETER="python3"

# --- Script Start ---
echo "INFO: Starting test execution script using tox..."
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR" # Ensure we are in the project root where tox.ini is

# 1. Ensure uv is installed (for installing tox if needed)
if ! command -v uv &> /dev/null; then
    echo "ERROR: uv command not found. Please install uv first."
    echo "       You can typically install it using: pip install uv"
    exit 1
fi

# 2. Setup virtual environment for tox itself (if not already done by another run_ script)
echo "INFO: Ensuring tox is installed in '$VENV_DIR_TOOLS' using '$PYTHON_INTERPRETER'..."
if ! uv venv "$VENV_DIR_TOOLS" --python "$PYTHON_INTERPRETER"; then
    echo "ERROR: Failed to create/update tools virtual environment '$VENV_DIR_TOOLS'. Ensure '$PYTHON_INTERPRETER' is valid."
    exit 1
fi

# Determine the Python executable path within the tools venv
PYTHON_IN_TOOLS_VENV="$VENV_DIR_TOOLS/bin/python"
if [ ! -f "$PYTHON_IN_TOOLS_VENV" ]; then
    # Fallback for Windows-style venv path if bin/python doesn't exist
    if [ -f "$VENV_DIR_TOOLS/Scripts/python.exe" ]; then
        PYTHON_IN_TOOLS_VENV="$VENV_DIR_TOOLS/Scripts/python.exe"
    else
        echo "ERROR: Python executable not found in tools virtual environment path: $VENV_DIR_TOOLS/bin/python or $VENV_DIR_TOOLS/Scripts/python.exe"
        exit 1
    fi
fi

# Install tox into the tools virtual environment
if ! uv pip install tox --python "$PYTHON_IN_TOOLS_VENV"; then
    echo "ERROR: Failed to install tox into '$VENV_DIR_TOOLS'."
    exit 1
else
    echo "INFO: tox installed/verified in '$VENV_DIR_TOOLS'."
fi

# 3. Run tox
# Tox will read tox.ini, create its own isolated environments (usually in a .tox/ directory),
# install dependencies as specified in tox.ini (from requirements.txt & test-requirements.txt),
# and then run the commands specified in tox.ini (pytest --cov=goodmem_client).
# We pass all arguments given to run_tests.sh ($@) along to tox.
echo "INFO: Executing tox..."
if "$PYTHON_IN_TOOLS_VENV" -m tox "$@"; then
    echo "INFO: Tox execution completed successfully."
else
    echo "ERROR: Tox execution failed. See output above for details."
    exit 1
fi

echo "INFO: Test execution script finished."
