#!/bin/bash
# =============================================================================
# Claude Code in VS Code — One-Line Installer (macOS)
# Run: curl -fsSL https://aiserviceengine.com/claude-code-install/setup.sh | bash
# =============================================================================
#
# Installs everything you need to use Claude Code inside VS Code:
#   1. Homebrew         (the macOS package manager)
#   2. VS Code          (the editor)
#   3. Claude Code      (the official native CLI — auto-updates)
#   4. VS Code extension (Anthropic's Claude Code panel)
#
# After the script finishes, open VS Code, click the Spark icon in the
# Activity Bar (left sidebar), and sign into your Claude account.
#
# =============================================================================

# When this script is piped via `curl | bash`, stdin is the script pipe.
# Subprocesses (notably `brew install --cask`) consume bytes from that pipe
# and can truncate the rest of the script. Re-exec from a temp file with
# stdin pointed at the terminal so interactive prompts still work.
if [ ! -t 0 ] && [ -z "$_CLAUDE_INSTALL_REEXEC" ]; then
    SCRIPT_TMP=$(mktemp) || { echo "Failed to create temp file" >&2; exit 1; }
    cat > "$SCRIPT_TMP"
    trap 'rm -f "$SCRIPT_TMP"' EXIT
    _CLAUDE_INSTALL_REEXEC=1 exec bash "$SCRIPT_TMP" < /dev/tty
fi

set -e

GREEN=$'\033[0;32m'
RED=$'\033[0;31m'
YELLOW=$'\033[1;33m'
BLUE=$'\033[0;34m'
BOLD=$'\033[1m'
NC=$'\033[0m'

pass() { echo -e "  ${GREEN}✓${NC} $1"; }
fail() { echo -e "  ${RED}✗${NC} $1"; }
info() { echo -e "  ${BLUE}→${NC} $1"; }
warn() { echo -e "  ${YELLOW}!${NC} $1"; }
header() { echo -e "\n${BOLD}━━━ $1 ━━━${NC}\n"; }
wait_enter() { read -r -p "$1" </dev/tty; }

# -----------------------------------------------------------------------------
# Mac-only guard
# -----------------------------------------------------------------------------
if [ "$(uname)" != "Darwin" ]; then
    echo -e "${RED}This installer is for macOS only.${NC}"
    echo "On Windows or Linux, follow the official install:"
    echo "  https://code.claude.com/docs/en/quickstart"
    exit 1
fi

# -----------------------------------------------------------------------------
header "Claude Code in VS Code — Installer"
echo "This installs Homebrew, VS Code, the Claude Code CLI, and the VS"
echo "Code extension. Existing installs are kept and not re-downloaded."
echo ""
echo "Estimated time: 3-5 minutes (depending on what you already have)."
echo ""
wait_enter "Press Enter to start..."

# -----------------------------------------------------------------------------
header "Step 1/4: Homebrew"

if command -v brew &> /dev/null; then
    pass "Homebrew already installed ($(brew --version | head -1))"
else
    info "Installing Homebrew (you may be prompted for your Mac password)..."
    /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" </dev/tty

    if [ -f /opt/homebrew/bin/brew ]; then
        eval "$(/opt/homebrew/bin/brew shellenv)"
        SHELL_PROFILE="$HOME/.zprofile"
        if ! grep -q 'homebrew' "$SHELL_PROFILE" 2>/dev/null; then
            echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> "$SHELL_PROFILE"
        fi
    elif [ -f /usr/local/bin/brew ]; then
        eval "$(/usr/local/bin/brew shellenv)"
    fi

    if command -v brew &> /dev/null; then
        pass "Homebrew installed"
    else
        fail "Homebrew install failed. Restart Terminal and run this script again."
        exit 1
    fi
fi

# -----------------------------------------------------------------------------
header "Step 2/4: VS Code"

if command -v code &> /dev/null; then
    pass "VS Code already installed and on PATH"
elif [ -d "/Applications/Visual Studio Code.app" ]; then
    info "VS Code app found. Adding 'code' command to PATH..."
    export PATH="/Applications/Visual Studio Code.app/Contents/Resources/app/bin:$PATH"
    SHELL_PROFILE="$HOME/.zprofile"
    if ! grep -q 'Visual Studio Code' "$SHELL_PROFILE" 2>/dev/null; then
        echo 'export PATH="/Applications/Visual Studio Code.app/Contents/Resources/app/bin:$PATH"' >> "$SHELL_PROFILE"
    fi
    pass "VS Code 'code' command added to PATH"
else
    info "Installing VS Code via Homebrew..."
    brew install --cask visual-studio-code
    if ! command -v code &> /dev/null; then
        export PATH="/Applications/Visual Studio Code.app/Contents/Resources/app/bin:$PATH"
        echo 'export PATH="/Applications/Visual Studio Code.app/Contents/Resources/app/bin:$PATH"' >> "$HOME/.zprofile"
    fi
    pass "VS Code installed"
fi

# -----------------------------------------------------------------------------
header "Step 3/4: Claude Code (native CLI)"
# Anthropic's official install — auto-updating native binary, no Node required.
# Source: https://code.claude.com/docs/en/quickstart

if command -v claude &> /dev/null; then
    pass "Claude Code already installed ($(claude --version 2>/dev/null | head -1))"
else
    info "Installing Claude Code via the official native installer..."
    curl -fsSL https://claude.ai/install.sh | bash </dev/tty

    [ -f "$HOME/.zprofile" ] && source "$HOME/.zprofile" 2>/dev/null || true
    [ -f "$HOME/.zshrc" ] && source "$HOME/.zshrc" 2>/dev/null || true

    if command -v claude &> /dev/null; then
        pass "Claude Code installed ($(claude --version 2>/dev/null | head -1))"
    else
        warn "Claude Code installed but not yet on PATH for this session."
        warn "Restart Terminal after this script finishes and run: claude --version"
    fi
fi

# -----------------------------------------------------------------------------
header "Step 4/4: VS Code Extension"

if code --list-extensions 2>/dev/null | grep -q "anthropic.claude-code"; then
    pass "Claude Code VS Code extension already installed"
else
    info "Installing Claude Code VS Code extension..."
    code --install-extension anthropic.claude-code 2>&1 | tail -1
    if code --list-extensions 2>/dev/null | grep -q "anthropic.claude-code"; then
        pass "Claude Code VS Code extension installed"
    else
        warn "Extension install may have failed. Install manually:"
        warn "  Open VS Code → Cmd+Shift+X → search 'Claude Code' → Install."
    fi
fi

# -----------------------------------------------------------------------------
header "Verification"

ALL_GOOD=true
command -v brew   &> /dev/null && pass "Homebrew: $(brew --version | head -1)" || { fail "Homebrew missing"; ALL_GOOD=false; }
command -v code   &> /dev/null && pass "VS Code: installed"                    || { fail "VS Code missing";  ALL_GOOD=false; }
command -v claude &> /dev/null && pass "Claude Code CLI: $(claude --version 2>/dev/null | head -1)" || warn "Claude Code CLI may need Terminal restart"
code --list-extensions 2>/dev/null | grep -q "anthropic.claude-code" \
    && pass "VS Code extension: installed" \
    || { fail "VS Code extension missing"; ALL_GOOD=false; }

# -----------------------------------------------------------------------------
echo ""
echo ""

if [ "$ALL_GOOD" = true ]; then
    echo -e "${GREEN}${BOLD}━━━ ALL DONE ━━━${NC}"
    echo ""
    echo "Everything is installed. Two manual steps left:"
    echo ""
    echo -e "  ${BOLD}1.${NC} Open VS Code:"
    echo "       open -a 'Visual Studio Code'"
    echo ""
    echo -e "  ${BOLD}2.${NC} Click the ${BOLD}Spark icon${NC} in the left Activity Bar"
    echo "       (or press ${BOLD}Cmd+Shift+P${NC} and type 'Claude Code') and sign in"
    echo "       with your Claude account (Pro, Max, Team, Enterprise, or Console)."
    echo ""
    echo -e "Then ask Claude anything in the chat panel. You're done."
else
    echo -e "${YELLOW}${BOLD}━━━ ALMOST DONE ━━━${NC}"
    echo ""
    echo "Some items need attention (see the red items above)."
    echo "Restart Terminal and run this script again, or follow the official"
    echo "install guide: https://code.claude.com/docs/en/quickstart"
fi

echo ""
