#!/usr/bin/env bash

set -euo pipefail

usage() {
  cat <<'EOF'
Usage: scripts/install_rc.sh [--editable] [--source PATH_OR_URL]

Installs the Research Capacitor CLI into an isolated virtual environment and
symlinks the `rc` command into ~/.local/bin by default.

Options:
  --editable          Install in editable mode.
  --source <value>    Install from a local path or pip-compatible URL.
  --help              Show this help message.

Environment overrides:
  RC_INSTALL_HOME     Base directory for the managed virtual environment.
  RC_BIN_DIR          Directory where the `rc` symlink will be written.
EOF
}

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"

SOURCE="${REPO_ROOT}"
EDITABLE=0

while [[ $# -gt 0 ]]; do
  case "$1" in
    --editable)
      EDITABLE=1
      shift
      ;;
    --source)
      if [[ $# -lt 2 ]]; then
        echo "error: --source requires a value" >&2
        exit 1
      fi
      SOURCE="$2"
      shift 2
      ;;
    --help|-h)
      usage
      exit 0
      ;;
    *)
      echo "error: unknown argument: $1" >&2
      usage >&2
      exit 1
      ;;
  esac
done

if ! command -v python3 >/dev/null 2>&1; then
  echo "error: python3 is required to install rc" >&2
  exit 1
fi

INSTALL_HOME="${RC_INSTALL_HOME:-$HOME/.local/share/research-capacitor}"
BIN_DIR="${RC_BIN_DIR:-$HOME/.local/bin}"
VENV_DIR="${INSTALL_HOME}/venv"

mkdir -p "${INSTALL_HOME}" "${BIN_DIR}"

echo "Creating managed environment at ${VENV_DIR}"
python3 -m venv "${VENV_DIR}"

PIP_BIN="${VENV_DIR}/bin/pip"
RC_BIN="${VENV_DIR}/bin/rc"
LINK_PATH="${BIN_DIR}/rc"

PIP_ARGS=("${SOURCE}")
if [[ ${EDITABLE} -eq 1 ]]; then
  PIP_ARGS=("-e" "${SOURCE}")
fi

echo "Installing rc from ${SOURCE}"
"${PIP_BIN}" install --upgrade pip
"${PIP_BIN}" install "${PIP_ARGS[@]}"

ln -sf "${RC_BIN}" "${LINK_PATH}"

echo
echo "Installed rc to ${RC_BIN}"
echo "Linked command to ${LINK_PATH}"
echo
"${LINK_PATH}" --help >/dev/null
echo "rc is ready."

case ":$PATH:" in
  *":${BIN_DIR}:"*)
    ;;
  *)
    echo
    echo "Add ${BIN_DIR} to your PATH to run \`rc\` from new shells."
    ;;
esac
