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

PACKAGE="@receiptor/cli"
NPM_PREFIX="${HOME}/.local"
NPM_BIN="${NPM_PREFIX}/bin"
BUN_BIN="${HOME}/.bun/bin"

say() {
  printf 'receiptor-install: %s\n' "$*"
}

fail() {
  say "$*" >&2
  exit 1
}

has_cmd() {
  command -v "$1" >/dev/null 2>&1
}

detect_shell_rc() {
  if [[ -n "${ZSH_VERSION:-}" ]]; then
    printf '%s' "${HOME}/.zshrc"
    return
  fi

  if [[ -n "${BASH_VERSION:-}" ]]; then
    printf '%s' "${HOME}/.bashrc"
    return
  fi

  printf '%s' "${HOME}/.profile"
}

print_path_instructions() {
  local bin_dir="$1"
  local shell_rc
  shell_rc="$(detect_shell_rc)"

  say "Add ${bin_dir} to your PATH, then restart your shell:"
  say "  echo 'export PATH=\"${bin_dir}:\$PATH\"' >> ${shell_rc}"
  say "  export PATH=\"${bin_dir}:\$PATH\""
}

install_with_npm() {
  say "Installing ${PACKAGE} with npm into ${NPM_PREFIX}"
  mkdir -p "${NPM_PREFIX}"
  npm install --global --prefix "${NPM_PREFIX}" "${PACKAGE}"
  printf '%s' "${NPM_BIN}"
}

install_with_bun() {
  say "Installing ${PACKAGE} with bun"
  bun install --global "${PACKAGE}"
  printf '%s' "${BUN_BIN}"
}

main() {
  local bin_dir=""

  if has_cmd npm; then
    bin_dir="$(install_with_npm)"
  elif has_cmd bun; then
    bin_dir="$(install_with_bun)"
  else
    fail "npm or bun is required. Install Node.js 20+ or Bun and try again."
  fi

  if [[ ! -x "${bin_dir}/receiptor" ]] && ! has_cmd receiptor; then
    fail "Receiptor CLI installation completed, but the receiptor binary was not found."
  fi

  say "Receiptor CLI installed."

  if ! has_cmd receiptor; then
    print_path_instructions "${bin_dir}"
  fi

  say "Next steps:"
  say "  receiptor --help"
  say "  receiptor auth sk_your_api_key"
  say "  receiptor workspace list"
}

main "$@"
