#!/bin/sh
# shellcheck shell=dash

set -u

APP_NAME="altertable"
BASE_URL="https://github.com/altertable-ai/altertable-cli/releases/latest/download"
INSTALL_DIR="$HOME/.local/bin"
PATH_BLOCK_START="# >>> altertable initialize >>>"
PATH_READY_IN_NEW_SHELL=0

append_path_block() {
  config_file="$1"
  config_kind="$2"
  if [ -f "$config_file" ] && grep -Fq "$PATH_BLOCK_START" "$config_file"; then
    printf "PATH setup already exists in %s.\n" "$config_file"
    return
  fi

  if ! mkdir -p "$(dirname "$config_file")"; then
    printf "Warning: could not create the directory for %s.\n" "$config_file"
    return 1
  fi

  if [ -s "$config_file" ] && [ -n "$(tail -c 1 "$config_file")" ]; then
    if ! printf '\n' >> "$config_file"; then
      printf "Warning: could not update PATH in %s.\n" "$config_file"
      return 1
    fi
  fi

  if [ "$config_kind" = "fish" ]; then
    # The shell variables below must remain literal for Fish to expand later.
    # shellcheck disable=SC2016
    if ! {
      printf '%s\n' "$PATH_BLOCK_START"
      printf 'if not contains -- "$HOME/.local/bin" $PATH\n'
      printf '  set -gx PATH "$HOME/.local/bin" $PATH\n'
      printf 'end\n'
      printf '# <<< altertable initialize <<<\n'
    } >> "$config_file"; then
      printf "Warning: could not update PATH in %s.\n" "$config_file"
      return 1
    fi
  else
    # The shell variables below must remain literal for Bash or Zsh to expand later.
    # shellcheck disable=SC2016
    if ! {
      printf '%s\n' "$PATH_BLOCK_START"
      printf 'case ":${PATH:-}:" in\n'
      printf '  *":$HOME/.local/bin:"*) ;;\n'
      printf '  *) export PATH="$HOME/.local/bin${PATH:+:$PATH}" ;;\n'
      printf 'esac\n'
      printf '# <<< altertable initialize <<<\n'
    } >> "$config_file"; then
      printf "Warning: could not update PATH in %s.\n" "$config_file"
      return 1
    fi
  fi

  printf "Updated PATH in %s.\n" "$config_file"
}

configure_path() {
  case ":${PATH:-}:" in
    *":$INSTALL_DIR:"*)
      printf "%s is already on PATH.\n" "$INSTALL_DIR"
      return
      ;;
  esac

  if [ "${ALTERTABLE_NO_PATH_UPDATE:-0}" = "1" ]; then
    printf "Skipped persistent PATH setup because ALTERTABLE_NO_PATH_UPDATE=1.\n"
    return
  fi

  shell_path="${SHELL:-}"
  shell_name="${shell_path##*/}"
  case "$shell_name" in
    bash)
      bashrc_ready=0
      login_ready=0
      if append_path_block "$HOME/.bashrc" "posix"; then
        bashrc_ready=1
      fi

      if [ -e "$HOME/.bash_profile" ]; then
        login_config_file="$HOME/.bash_profile"
      elif [ -e "$HOME/.bash_login" ]; then
        login_config_file="$HOME/.bash_login"
      else
        login_config_file="$HOME/.profile"
      fi
      if append_path_block "$login_config_file" "posix"; then
        login_ready=1
      fi
      if [ "$bashrc_ready" = "1" ] && [ "$login_ready" = "1" ]; then
        PATH_READY_IN_NEW_SHELL=1
      fi
      ;;
    zsh)
      if append_path_block "${ZDOTDIR:-$HOME}/.zshrc" "posix"; then
        PATH_READY_IN_NEW_SHELL=1
      fi
      ;;
    fish)
      if append_path_block "${XDG_CONFIG_HOME:-$HOME/.config}/fish/conf.d/altertable.fish" "fish"; then
        PATH_READY_IN_NEW_SHELL=1
      fi
      ;;
    *)
      printf "Could not configure PATH automatically for %s.\n" "${SHELL:-an unknown shell}"
      ;;
  esac
}

detect_platform() {
  OS="$(uname -s)"
  ARCH="$(uname -m)"

  case "$OS" in
    Linux)  os="linux" ;;
    Darwin) os="darwin" ;;
    *)
      echo "❌ Unsupported operating system: $OS"
      exit 1
      ;;
  esac

  case "$ARCH" in
    x86_64|amd64)  arch="x64" ;;
    aarch64|arm64) arch="arm64" ;;
    *)
      echo "❌ Unsupported architecture: $ARCH"
      exit 1
      ;;
  esac

  echo "${os}-${arch}"
}

PLATFORM="$(detect_platform)"
DOWNLOAD_URL="${BASE_URL}/altertable-${PLATFORM}"

echo "Installing Altertable CLI for ${PLATFORM}..."
mkdir -p "$INSTALL_DIR"

if ! output="$(curl -LsSf "$DOWNLOAD_URL" -o "$INSTALL_DIR/$APP_NAME" 2>&1)"; then
  echo "❌ Failed to download $APP_NAME for ${PLATFORM}"
  echo "$output"
  exit 1
fi

chmod +x "$INSTALL_DIR/$APP_NAME"
configure_path

printf "\n🎉 Altertable CLI installed successfully!\n"
printf "\nRun %s/%s --help now.\n" "$INSTALL_DIR" "$APP_NAME"
if [ "$PATH_READY_IN_NEW_SHELL" = "1" ]; then
  printf "Open a new shell to run \`altertable --help\` directly.\n"
fi
printf "Set ALTERTABLE_NO_PATH_UPDATE=1 to skip persistent PATH setup.\n"
printf "\nNeed help? See https://altertable.ai/docs\n"
