#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")"

if command -v python3.14 >/dev/null 2>&1; then
  PYTHON_BIN=python3.14
else
  PYTHON_BIN=python3
fi

echo "Using Python: $($PYTHON_BIN --version 2>&1)"

TARGET_MM=$("$PYTHON_BIN" -c 'import sys; print(f"{sys.version_info[0]}.{sys.version_info[1]}")')
CURRENT_MM=""
if [ -x .venv/bin/python ]; then
  CURRENT_MM=$(.venv/bin/python -c 'import sys; print(f"{sys.version_info[0]}.{sys.version_info[1]}")')
fi

if [ ! -d .venv ] || [ "$CURRENT_MM" != "$TARGET_MM" ]; then
  rm -rf .venv
  "$PYTHON_BIN" -m venv .venv
fi

source .venv/bin/activate
python -m pip install --upgrade pip
python -m pip install -r requirements.txt
exec python -m uvicorn app.main:app --host 127.0.0.1 --port 8765
