#!/usr/bin/env bash
# script/_lib/python_runner.sh — Resolve Python interpreter for module invocation.
#
# Resolution order:
#   1. uv python find (asks uv for the project interpreter)
#   2. $VIRTUAL_ENV python (set by "uv run" or manual activation)
#   3. python3 on PATH
#   4. python on PATH
#
# Usage:
#   source script/_lib/python_runner.sh
#   run_py_module <module> [args...]
#   run_py_script <script> [args...]

_resolve_python() {
  # 1. Ask uv for the project interpreter (most reliable inside uv run).
  if command -v uv >/dev/null 2>&1; then
    local _uv_py
    _uv_py="$(uv python find 2>/dev/null || true)"
    if [ -n "${_uv_py}" ] && [ -x "${_uv_py}" ]; then
      echo "${_uv_py}"
      return 0
    fi
  fi
  # 2. VIRTUAL_ENV (set by uv run or manual activation).
  if [ -n "${VIRTUAL_ENV:-}" ]; then
    if [ -x "$VIRTUAL_ENV/Scripts/python.exe" ]; then
      echo "$VIRTUAL_ENV/Scripts/python.exe"
      return 0
    elif [ -x "$VIRTUAL_ENV/bin/python" ]; then
      echo "$VIRTUAL_ENV/bin/python"
      return 0
    fi
  fi
  # 3. python3 on PATH.
  if command -v python3 >/dev/null 2>&1; then
    echo "python3"
    return 0
  fi
  # 4. python on PATH.
  if command -v python >/dev/null 2>&1; then
    echo "python"
    return 0
  fi
  echo "ERROR: Python not found. Run: uv run --group dev bash script/verify" >&2
  return 1
}

run_py_module() {
  local py
  py=$(_resolve_python) || exit 1
  "$py" -m "$@"
}

run_py_script() {
  local py
  py=$(_resolve_python) || exit 1
  "$py" "$@"
}
