#!/usr/bin/env bash
set -euo pipefail

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

supports_project() {
  "$1" -c 'import sys, tomllib; raise SystemExit(sys.version_info < (3, 11))' \
    >/dev/null 2>&1
}

# Prefer the checkout-owned environment, then explicit supported interpreter
# names. A generic `python3` is last because macOS/Xcode can resolve it to 3.9.
for candidate in \
  "$repo_root/.venv/bin/python3" \
  python3.14 python3.13 python3.12 python3.11 python3; do
  resolved="$(command -v "$candidate" 2>/dev/null || true)"
  if [[ -n "$resolved" ]] && supports_project "$resolved"; then
    exec "$resolved" "$@"
  fi
done

# uv is the repo's canonical environment owner and can provision a compatible
# interpreter when the host has none on PATH.
if command -v uv >/dev/null 2>&1; then
  exec uv run --project "$repo_root" --no-sync python "$@"
fi

printf '%s\n' \
  'vibecrafted: Python >=3.11 with stdlib tomllib is required; install uv or set PYTHON explicitly.' \
  >&2
exit 2
