#!/usr/bin/env bash
# Copyright the boost contributors.
# SPDX-License-Identifier: Apache-2.0
# boost — Homebrew for AI coding skills.
# Thin shim: finds Python 3.12+, runs the boost_cli package that lives
# next to this script (resolving symlinks, so `ln -s .../boost ~/bin/boost`
# just works). No PyPI, no Artifactory — stdlib only.
set -euo pipefail

SOURCE="${BASH_SOURCE[0]:-$0}"
while [ -h "$SOURCE" ]; do
  DIR="$(cd -P "$(dirname "$SOURCE")" >/dev/null 2>&1 && pwd)"
  SOURCE="$(readlink "$SOURCE")"
  [[ "$SOURCE" != /* ]] && SOURCE="$DIR/$SOURCE"
done
ROOT="$(cd -P "$(dirname "$SOURCE")" >/dev/null 2>&1 && pwd)"
# Under Git Bash on Windows, $ROOT is an MSYS path (/d/a/boost/boost); native
# Windows Python can't resolve that, so convert to a mixed path (D:/a/...)
# before it's embedded in the -c script below. No-op on Linux/macOS.
if command -v cygpath >/dev/null 2>&1; then
  ROOT="$(cygpath -m "$ROOT")"
fi

# `python3` first: an activated venv (where `boost doctor`'s `[rag]` hint
# installs the extra) shadows it, and a versioned name ahead of it would pick
# a Homebrew python3.14 over that venv's 3.12 and hide the extra again. Then
# the versioned names, because `brew install python@3.13` and `apt install
# python3.13` (README's own remedy) link only `python3.13`, leaving the old
# system `python3` first on PATH. The probe gates every candidate, so the
# order only decides which of several new-enough interpreters wins.
find_python() {
  for py in python3 python3.15 python3.14 python3.13 python3.12 python; do
    if command -v "$py" >/dev/null 2>&1; then
      if "$py" -c 'import sys; sys.exit(0 if sys.version_info >= (3, 12) else 1)' 2>/dev/null; then
        echo "$py"
        return 0
      fi
    fi
  done
  return 1
}

PY="$(find_python)" || {
  echo "boost: Python 3.12+ is required but was not found on PATH" >&2
  echo "  hint: brew install python@3.13 (or: sudo apt install python3.13)" >&2
  exit 1
}

# No -S: site-packages must stay visible, or an optional extra installed into
# this interpreter (`boost doctor`'s own `[rag]` hint) can never be imported.
# The checkout still wins over any installed copy: it is sys.path[0].
exec "$PY" -c "
import sys
sys.path.insert(0, '$ROOT')
from boost_cli.cli import main
sys.exit(main(sys.argv[1:]))
" "$@"
