#!/usr/bin/env zsh

# Fix NVM/NPM conflicts for agent performance
# This script patches .zshrc to make it agent-friendly

ZSHRC="$HOME/.zshrc"
BACKUP="$HOME/.zshrc.backup.$(date +%Y%m%d_%H%M%S)"

echo "🔧 Fixing .zshrc for agent performance..."

# Backup
cp "$ZSHRC" "$BACKUP"
echo "✅ Backup created: $BACKUP"

# Create patched version
cat > /tmp/zshrc_patch.txt << 'EOF'

# ========================================
# AGENT OPTIMIZATION - CONDITIONAL LOADING
# ========================================

# Only set NPM_CONFIG_PREFIX in interactive shells
if [[ -o interactive ]]; then
    export NPM_CONFIG_PREFIX="$HOME/.npm-global"
fi

# Load NVM only in interactive shells (not for agents)
export NVM_DIR="$HOME/.nvm"
if [[ -o interactive ]]; then
    [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" 2>/dev/null
    [ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" 2>/dev/null
fi

EOF

echo ""
echo "📝 Recommended changes to add to .zshrc:"
cat /tmp/zshrc_patch.txt
echo ""

read -q "REPLY?Apply these changes automatically? (y/n) "
echo ""

if [[ $REPLY =~ ^[Yy]$ ]]; then
    # Comment out existing NPM_CONFIG_PREFIX line
    sed -i '' 's/^export NPM_CONFIG_PREFIX=/#export NPM_CONFIG_PREFIX=/' "$ZSHRC"
    
    # Add patch at the end
    cat /tmp/zshrc_patch.txt >> "$ZSHRC"
    
    echo "✅ .zshrc patched successfully!"
    echo ""
    echo "🔄 Reload with: source ~/.zshrc"
    echo "🧪 Test with: zsh -lc 'echo test'"
else
    echo "⏭️  Skipped. You can manually add the content above to your .zshrc"
    echo "📄 Or copy from: /tmp/zshrc_patch.txt"
fi

rm /tmp/zshrc_patch.txt
