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

BASE_URL="https://releases.zero.xyz"
INSTALL_DIR="$HOME/.zero/bin"
BIN_NAME="zero"

# --- Detect OS and architecture ---
OS="$(uname -s)"
ARCH="$(uname -m)"

case "$OS" in
  Darwin) PLATFORM="macos" ;;
  Linux)  PLATFORM="linux" ;;
  *)
    echo "Error: unsupported OS: $OS" >&2
    exit 1
    ;;
esac

case "$ARCH" in
  arm64 | aarch64) ARCH_SUFFIX="arm64" ;;
  x86_64)          ARCH_SUFFIX="x64" ;;
  *)
    echo "Error: unsupported architecture: $ARCH" >&2
    exit 1
    ;;
esac

ASSET_NAME="zero-${PLATFORM}-${ARCH_SUFFIX}"
DOWNLOAD_URL="${BASE_URL}/latest/${ASSET_NAME}"

# --- Remove legacy npm-installed CLI if present ---
# Note: `npm ls -g <pkg>` and `pnpm ls -g <pkg>` both exit 0 even when the package
# isn't installed, so grep the output for the package name instead of relying on exit code.
if command -v npm &>/dev/null && npm ls -g --depth=0 2>/dev/null | grep -q '@zeroxyz/cli'; then
  echo "Found legacy @zeroxyz/cli npm package, removing..."
  npm uninstall -g @zeroxyz/cli 2>/dev/null || true
fi
if command -v pnpm &>/dev/null && pnpm ls -g --depth=0 2>/dev/null | grep -q '@zeroxyz/cli'; then
  echo "Found legacy @zeroxyz/cli pnpm package, removing..."
  pnpm remove -g @zeroxyz/cli 2>/dev/null || true
fi

# --- Download and install ---
echo "Downloading ${ASSET_NAME}..."
mkdir -p "$INSTALL_DIR"
curl -fsSL "$DOWNLOAD_URL" -o "${INSTALL_DIR}/${BIN_NAME}"
chmod +x "${INSTALL_DIR}/${BIN_NAME}"

# macOS: remove quarantine flag and ad-hoc sign so the kernel allows execution
if [ "$PLATFORM" = "macos" ]; then
  xattr -d com.apple.quarantine "${INSTALL_DIR}/${BIN_NAME}" 2>/dev/null || true
  codesign --sign - --force "${INSTALL_DIR}/${BIN_NAME}" 2>/dev/null || true
fi

echo "Installed zero to ${INSTALL_DIR}/${BIN_NAME}"

# --- Add to PATH if needed ---
PATH_RC_FILE=""
PATH_NEEDS_RELOAD=0

add_to_path() {
  local rc_file="$1"
  local line="export PATH=\"\$HOME/.zero/bin:\$PATH\""

  if [ -f "$rc_file" ] && grep -qF '.zero/bin' "$rc_file"; then
    PATH_RC_FILE="$rc_file"
    return
  fi

  echo "" >> "$rc_file"
  echo "# Zero CLI" >> "$rc_file"
  echo "$line" >> "$rc_file"
  echo "Added ${INSTALL_DIR} to PATH in ${rc_file}"
  PATH_RC_FILE="$rc_file"
  PATH_NEEDS_RELOAD=1
}

if [[ ":$PATH:" != *":$INSTALL_DIR:"* ]]; then
  SHELL_NAME="$(basename "$SHELL")"
  case "$SHELL_NAME" in
    zsh)  add_to_path "$HOME/.zshrc" ;;
    bash)
      if [ -f "$HOME/.bash_profile" ]; then
        add_to_path "$HOME/.bash_profile"
      else
        add_to_path "$HOME/.bashrc"
      fi
      ;;
    *)
      echo "Add ${INSTALL_DIR} to your PATH manually by adding this line to your shell's rc file:"
      echo "  export PATH=\"\$HOME/.zero/bin:\$PATH\""
      PATH_NEEDS_RELOAD=1
      ;;
  esac
  # Make `zero` resolvable for the remainder of this install script.
  export PATH="${INSTALL_DIR}:${PATH}"
fi

echo ""

# --- Run init ---
"${INSTALL_DIR}/${BIN_NAME}" init

# --- Final PATH reminder ---
# When PATH was just appended to an rc file, the parent shell (where `curl | bash`
# ran) still can't resolve `zero`. Tell the user how to pick up the change without
# opening a new terminal so the `zero ...` commands printed by `zero init` work.
if [ "$PATH_NEEDS_RELOAD" = "1" ]; then
  echo ""
  echo "============================================================"
  echo "  One more step: reload your shell so \`zero\` is on PATH."
  if [ -n "$PATH_RC_FILE" ]; then
    echo "    source \"$PATH_RC_FILE\"    # or: exec \$SHELL"
  else
    echo "    exec \$SHELL"
  fi
  echo "  Or open a new terminal. Then run the \`zero\` commands above."
  echo "============================================================"
fi
