#!/usr/bin/env bash
# Riposte launcher (Linux / macOS) -- run Riposte straight from a fresh clone, with NO
# virtualenv activation and NO per-machine setup.
#
#     git clone <repo> && cd Riposte
#     ./riposte tui
#     ./riposte scope verify --roe roe.yaml --target example.com
#
# On the FIRST run it bootstraps a local .venv next to this script and installs Riposte
# into it (editable). Every run after that just forwards your arguments to the CLI, so it
# is instant. Nothing is added to your PATH or shell profile; the .venv stays inside the
# repo (it is git-ignored).
#
# Extras: by default only the `tui` extra is installed (enough for `riposte tui`). Override
# with the RIPOSTE_EXTRAS env var, e.g.  RIPOSTE_EXTRAS=tui,llm,connect ./riposte tui
set -euo pipefail

here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
venv="$here/.venv"
exe="$venv/bin/riposte"

# Find a Python >= 3.11 (this project requires it). Try newest-named interpreters first,
# then bare python3/python, version-gating each so an old default is never used.
find_python() {
  local c
  for c in python3.14 python3.13 python3.12 python3.11 python3 python; do
    if command -v "$c" >/dev/null 2>&1; then
      if "$c" -c 'import sys; raise SystemExit(0 if sys.version_info[:2] >= (3, 11) else 1)' 2>/dev/null; then
        command -v "$c"
        return 0
      fi
    fi
  done
  return 1
}

if [ ! -x "$exe" ]; then
  echo "[riposte] first run: bootstrapping a local .venv (one-time)..." >&2

  if ! py="$(find_python)"; then
    echo "[riposte] Python 3.11+ was not found on PATH. Install it and re-run." >&2
    exit 1
  fi

  [ -d "$venv" ] || "$py" -m venv "$venv"

  extras="${RIPOSTE_EXTRAS:-tui}"
  ( cd "$here" \
      && "$venv/bin/python" -m pip install --upgrade pip \
      && "$venv/bin/python" -m pip install -e ".[$extras]" )

  if [ ! -x "$exe" ]; then
    echo "[riposte] bootstrap failed: $exe is still missing after install." >&2
    exit 1
  fi
  echo "[riposte] ready (installed extras: $extras). Launching..." >&2
fi

# Forward every argument to the real CLI (exec so signals + exit code pass through).
exec "$exe" "$@"
