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

BASE_URL="${BLISTECH_INSTALL_BASE_URL:-https://coder.blisshosts.com}"
BASE_URL="${BASE_URL%/}"
WHEEL_URL="${BLISTECH_WHEEL_URL:-$BASE_URL/downloads/blisscoder-cli-latest.whl}"
AUTH_API_BASE="${BLISTECH_AUTH_API_BASE:-https://auth.blisshosts.com}"
API_BASE="${BLISTECH_API_BASE:-https://coder.blisshosts.com/v1}"
PYTHON_BIN="${BLISTECH_PYTHON_BIN:-}"

pick_python() {
  if [[ -n "$PYTHON_BIN" && -x "$PYTHON_BIN" ]]; then
    printf '%s\n' "$PYTHON_BIN"
    return
  fi
  if command -v python3 >/dev/null 2>&1; then
    command -v python3
    return
  fi
  if command -v python >/dev/null 2>&1; then
    command -v python
    return
  fi
  echo "python3 is required" >&2
  exit 1
}

PYTHON_BIN="$(pick_python)"

if ! "$PYTHON_BIN" -m pip --version >/dev/null 2>&1; then
  "$PYTHON_BIN" -m ensurepip --upgrade >/dev/null 2>&1 || true
fi

if ! "$PYTHON_BIN" -m pip --version >/dev/null 2>&1; then
  echo "pip is required for the hosted installer" >&2
  exit 1
fi

"$PYTHON_BIN" -m pip install --user --upgrade "$WHEEL_URL"

USER_BIN_DIR="$($PYTHON_BIN - <<'PY'
from __future__ import annotations
import site
import sys
paths = [p for p in site.getuserbase(), site.getusersitepackages() if p]
if not paths:
    raise SystemExit('failed to resolve user install paths')
print(site.getuserbase() + '/bin')
PY
)"

printf '\nBlissCoder CLI installed.\n'
printf 'CLI paths:\n'
printf '  %s/blisscoder\n' "$USER_BIN_DIR"
printf '  %s/blistech (legacy alias)\n' "$USER_BIN_DIR"
printf 'If needed, add this to your shell profile:\n'
printf '  export PATH="%s:$PATH"\n' "$USER_BIN_DIR"
printf '\nNext steps:\n'
printf '  blisscoder --help\n'
printf '  blisscoder login --login-provider http --login-api-base %s --api-base %s\n' "$AUTH_API_BASE" "$API_BASE"
printf '  blisscoder doctor\n'
