#!/bin/bash
set -uo pipefail

SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
cd "$SCRIPT_DIR"

VERSIONS=("3.9" "3.10" "3.11" "3.12" "3.13" "3.14")

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BOLD='\033[1m'
RESET='\033[0m'

passed=()
failed=()
skipped=()

for ver in "${VERSIONS[@]}"; do
    py="python${ver}"

    if ! command -v "$py" &> /dev/null; then
        printf "${YELLOW}%-12s SKIPPED (not installed)${RESET}\n" "$py"
        skipped+=("$ver")
        continue
    fi

    printf "${BOLD}%-12s Running tests...${RESET}\n" "$py"

    venv_dir=$(mktemp -d)
    trap "rm -rf $venv_dir" EXIT

    "$py" -m venv "$venv_dir" 2>/dev/null
    if [ $? -ne 0 ]; then
        printf "${RED}%-12s FAILED (cannot create venv)${RESET}\n" "$py"
        failed+=("$ver")
        rm -rf "$venv_dir"
        continue
    fi

    "$venv_dir/bin/pip" install -q --disable-pip-version-check pytest pytest-asyncio 2>/dev/null
    "$venv_dir/bin/pip" install -q --disable-pip-version-check -e . 2>/dev/null

    output=$("$venv_dir/bin/python" -m pytest tests/ -v 2>&1)
    exit_code=$?

    if [ $exit_code -eq 0 ]; then
        printf "${GREEN}%-12s PASSED${RESET}\n" "$py"
        passed+=("$ver")
    else
        printf "${RED}%-12s FAILED (exit code: %d)${RESET}\n" "$py" "$exit_code"
        echo "$output" | tail -20
        failed+=("$ver")
    fi

    rm -rf "$venv_dir"
done

echo ""
echo "${BOLD}=== Summary ===${RESET}"
[ ${#passed[@]} -gt 0 ]  && printf "${GREEN}  Passed:  %s${RESET}\n" "${passed[*]}"
[ ${#failed[@]} -gt 0 ]  && printf "${RED}  Failed:  %s${RESET}\n" "${failed[*]}"
[ ${#skipped[@]} -gt 0 ] && printf "${YELLOW}  Skipped: %s${RESET}\n" "${skipped[*]}"

[ ${#failed[@]} -gt 0 ] && exit 1
exit 0
