#!/usr/bin/env bash
set -euo pipefail

DOWNLOAD_BASE_URL="${BIOSIMULANT_CLI_DOWNLOAD_BASE_URL:-https://staging-landing.internal.biosimulant.com/cli-releases}"
CHANNEL_OR_VERSION="${1:-stable}"

status() {
  echo "biosimulant: $*" >&2
}

resolve_version() {
  case "$CHANNEL_OR_VERSION" in
    stable|latest)
      curl -fsSL "$DOWNLOAD_BASE_URL/$CHANNEL_OR_VERSION" | tr -d '[:space:]'
      ;;
    *)
      printf '%s\n' "$CHANNEL_OR_VERSION"
      ;;
  esac
}

if ! command -v curl >/dev/null 2>&1; then
  echo "error: curl is required to resolve the pinned Biosimulant release" >&2
  exit 1
fi

VERSION="$(resolve_version)"
if [ -z "$VERSION" ]; then
  echo "error: could not resolve Biosimulant CLI version from $CHANNEL_OR_VERSION" >&2
  exit 1
fi

PACKAGE="biosimulant==$VERSION"
if command -v pipx >/dev/null 2>&1; then
  status "Installing $PACKAGE with pipx"
  pipx install --force "$PACKAGE"
elif command -v uv >/dev/null 2>&1; then
  status "pipx is unavailable; installing $PACKAGE with uv"
  uv tool install --force "$PACKAGE"
else
  echo "error: install pipx or uv, then retry" >&2
  echo "pipx: https://pipx.pypa.io/stable/installation/" >&2
  echo "uv:   https://docs.astral.sh/uv/getting-started/installation/" >&2
  exit 1
fi

biosimulant --version
echo "Biosimulant CLI $VERSION installed from PyPI"
