#!/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
}

# PYTHON selects one executable (a path or PATH command), never shell code or
# interpreter flags. An explicit selection must work; do not silently replace it.
if [[ ${PYTHON+x} ]]; then
  resolved="$(type -P -- "$PYTHON" 2>/dev/null || true)"
  if [[ -z "$resolved" || ! -f "$resolved" || ! -x "$resolved" ]]; then
    printf 'vibecrafted: explicit PYTHON is not an executable: %s\n' "$PYTHON" >&2
    exit 2
  fi
  # -ef compares file identity, including relative paths, symlinks and hardlinks.
  if [[ "$resolved" -ef "${BASH_SOURCE[0]}" ]]; then
    printf 'vibecrafted: explicit PYTHON resolves to project-python itself; refusing recursion.\n' >&2
    exit 2
  fi
  if ! supports_project "$resolved"; then
    printf 'vibecrafted: explicit PYTHON must support Python >=3.11 with stdlib tomllib: %s\n' "$PYTHON" >&2
    exit 2
  fi
  exec "$resolved" "$@"
fi

# Prefer the checkout-owned environment, then 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
