#!/bin/bash
# Codex Environment Setup for macOS
# Smart installer that works with existing tools

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

# Logging
log() { echo -e "${BLUE}==>${NC} $1"; }
success() { echo -e "${GREEN}✓${NC} $1"; }
warn() { echo -e "${YELLOW}⚠${NC} $1"; }
error() { echo -e "${RED}✗${NC} $1"; }

# Banner
echo -e "${BLUE}╔════════════════════════════════════╗"
echo -e "║ Codex CLI Quick Setup ║"
echo -e "╚════════════════════════════════════╝${NC}"
echo

# Quick environment check
log "Checking your environment..."

# Detect architecture for Homebrew paths
ARCH=$(uname -m)
if [[ "$ARCH" == "arm64" ]]; then
    BREW_PREFIX="/opt/homebrew"
else
    BREW_PREFIX="/usr/local"
fi

# Check what's already installed
has_node=false
has_npm=false
node_version_ok=false

# Check Homebrew
if command -v brew >/dev/null 2>&1; then
    success "Homebrew $(brew --version | head -1 | cut -d' ' -f2)"
fi

# Check Node.js
if command -v node &>/dev/null; then
    has_node=true
    node_version=$(node -v | sed 's/v//')
    major_version=$(echo $node_version | cut -d. -f1)
    if [ "$major_version" -ge 18 ]; then
        node_version_ok=true
        success "Node.js v$node_version"
    else
        warn "Node.js v$node_version (needs upgrade to v18+)"
    fi
fi

# Check npm
if command -v npm &>/dev/null; then
    has_npm=true
    success "npm v$(npm -v)"
fi

# Check Git
if command -v git &>/dev/null; then
    success "Git $(git --version | cut -d' ' -f3)"
fi

# Install only what's needed
echo

# Homebrew - only if missing
if ! command -v brew >/dev/null 2>&1; then
    log "Installing Homebrew..."
    if /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"; then
        # Use the pre-detected BREW_PREFIX
        eval "$($BREW_PREFIX/bin/brew shellenv)"
        
        # Verify installation
        if command -v brew >/dev/null 2>&1; then
            success "Homebrew installed successfully"
        else
            error "Homebrew installation verification failed"
            exit 1
        fi
    else
        error "Homebrew installation failed"
        exit 1
    fi
else
    success "Homebrew already installed"
fi

# Node.js - only if missing or outdated
if [ "$has_node" = false ] || [ "$node_version_ok" = false ]; then
    echo
    log "Node.js 18+ required for Codex"
    
    # Check if brew is available
    if command -v brew >/dev/null 2>&1; then
        log "Installing Node.js LTS via Homebrew..."
        brew install node || brew upgrade node
        success "Node.js installed"
    elif command -v nvm &>/dev/null || [ -f "$HOME/.nvm/nvm.sh" ]; then
        log "Installing Node.js LTS via nvm..."
        export NVM_DIR="$HOME/.nvm"
        [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
        nvm install --lts
        nvm use --lts
        success "Node.js installed via nvm"
    else
        error "Please install Node.js 18+ from https://nodejs.org/"
        echo "Or install via Homebrew: brew install node"
        exit 1
    fi
fi

# Quick npm setup
if command -v npm &>/dev/null; then
    # Ensure we're using official registry for @openai packages
    current_registry=$(npm config get registry)
    if [[ "$current_registry" != *"registry.npmjs.org"* ]]; then
        log "Switching to official npm registry..."
        npm config set registry https://registry.npmjs.org/
    fi
else
    error "npm not found. Please check your Node.js installation."
    exit 1
fi

# Install Codex CLI
echo
log "Installing Codex CLI..."

# Check

npm install -g @openai/codex@latest


# Final check
echo
echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
if command -v codex &>/dev/null; then
    codex_version=$(codex --version 2>/dev/null || echo "ready")
    success "Codex is ready! Version: $codex_version"
    echo
    echo "Get started:"
    echo " $ cd your-project"
    echo " $ codex"
else
    error "Codex command not found"
    echo "Try opening a new terminal or run:"
    echo " $ source ~/.zshrc"
    echo " $ source ~/.bash_profile"
fi
echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"