#!/bin/bash
# flowctl wrapper — invokes the source-first bootstrap beside flowctl.py via a
# probed Python 3.11+ interpreter.
#
# SELF-CONTAINED: this launcher does NOT source scripts/lib/pick-python.sh —
# installed copies (.flow/bin/flowctl, scripts/ralph/flowctl) can't assume that
# path is reachable. Keep this inline probe in sync with the shared resolver at
# plugins/flow-next/scripts/lib/pick-python.sh.
#
# Probe = functionality + minimum version: each candidate must actually run and
# report Python 3.11+, so the Windows Store `python3` App Execution Alias stub
# and working-but-too-old interpreters are skipped. Candidate order:
#   $PYTHON_BIN (scalar override) -> py -3 -> python3 -> python
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
FLOWCTL_SOURCE_DIR="$SCRIPT_DIR"

FLOW_PY=()
FLOW_PY_TOO_OLD=()
for _cand in "${PYTHON_BIN:-}" "py -3" "python3" "python"; do
  [ -n "$_cand" ] || continue
  # Intentional word-split so the two-word `py -3` becomes two argv elements.
  read -r -a _argv <<< "$_cand"
  [ "${#_argv[@]}" -gt 0 ] || continue
  if "${_argv[@]}" -c "import sys; raise SystemExit(0 if sys.version_info >= (3, 11) else 3)" >/dev/null 2>&1; then
    FLOW_PY=("${_argv[@]}")
    break
  elif [ "$?" -eq 3 ]; then
    FLOW_PY_TOO_OLD+=("$_cand")
  fi
done

if [ "${#FLOW_PY[@]}" -eq 0 ]; then
  if [ "${#FLOW_PY_TOO_OLD[@]}" -gt 0 ]; then
    echo "flowctl: Python 3.11 or newer is required; working but too-old candidate(s): ${FLOW_PY_TOO_OLD[*]}." >&2
    echo "  Install a supported Python, or set PYTHON_BIN to its command name." >&2
  else
    echo "flowctl: no working Python interpreter found (tried \$PYTHON_BIN, py -3, python3, python)." >&2
    echo "  On Windows, 'python3' may be the disabled Microsoft Store alias stub;" >&2
    echo "  install python.org Python (or the py launcher), or set PYTHON_BIN to a working interpreter." >&2
  fi
  exit 1
fi

FLOWCTL_ENTRY="$FLOWCTL_SOURCE_DIR/flowctl.py"
if [ "$#" -eq 1 ] && { [ "$1" = "usage" ] || [ "$1" = "--help" ]; } \
  && [ -f "$FLOWCTL_SOURCE_DIR/flowctl_bootstrap.py" ]; then
  FLOWCTL_ENTRY="$FLOWCTL_SOURCE_DIR/flowctl_bootstrap.py"
fi
exec "${FLOW_PY[@]}" "$FLOWCTL_ENTRY" "$@"
