#!/bin/bash
# ============================================================
# claude.sh — Claude Code CLI (Anthropic)
# ============================================================
# Installs Claude Code, Anthropic's official AI-powered CLI
# coding assistant, as a global npm package.
#
# Claude Code requires Node.js / npm.  The script first checks
# whether npm is already on PATH; if not, it attempts to
# activate nvm (Node Version Manager) from the default location
# ~/.nvm so the correct Node.js version is available before
# running the install.
#
# This is an optional module because Claude Code is only useful
# to developers who want AI-assisted coding inside the terminal,
# and it requires an Anthropic API key to function.
# ============================================================

set -euo pipefail
# Load shared logging helpers from the dotfiles lib
source "$(dirname "${BASH_SOURCE[0]}")/../../lib/logging.sh"

log "Installing Claude Code via npm..."

# Check whether npm is already available on PATH.
# If not, try to source nvm so it places the correct npm into PATH.
# This handles the common case where Node.js was installed through nvm
# rather than pacman, meaning it isn't in the system PATH by default.
if ! command -v npm &>/dev/null; then
    log "Sourcing nvm to get npm..."
    export NVM_DIR="$HOME/.nvm"
    # nvm.sh sets up the nvm function and adds the active Node.js to PATH.
    # The -s test checks that the file exists and is non-empty before sourcing.
    [[ -s "$NVM_DIR/nvm.sh" ]] && source "$NVM_DIR/nvm.sh"
fi

# Install Claude Code globally so the `claude` command is available system-wide.
# -g installs to the global npm prefix (typically ~/.nvm/versions/node/<ver>/lib
# when using nvm, or /usr/local/lib when using system npm).
npm install -g @anthropic-ai/claude-code

log "Claude Code installed."
