#!/usr/bin/env zsh

# Clean and fix .zshrc for agent optimization
# Removes duplicates and fixes NPM_CONFIG_PREFIX issues

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

echo "🔧 Cleaning .zshrc..."

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

# Remove the orphan ZSHRC line
sed -i '' '/^ZSHRC$/d' "$ZSHRC"
echo "✅ Removed orphan ZSHRC line"

# Remove all NPM_CONFIG_PREFIX and NVM sections
sed -i '' '/# AGENT OPTIMIZATION/,/fi$/d' "$ZSHRC"
echo "✅ Removed duplicate agent optimization sections"

# Fix the PATH line that references NPM_CONFIG_PREFIX
sed -i '' 's|export PATH="$NPM_CONFIG_PREFIX/bin:\([^"]*\)"|export PATH="$HOME/.npm-global/bin:\1"|' "$ZSHRC"
echo "✅ Fixed PATH to use hardcoded npm-global path"

# Add clean agent optimization at the end
cat >> "$ZSHRC" << 'EOF'

# ========================================
# AGENT OPTIMIZATION (Added automatically)
# ========================================

# NVM setup - only in interactive shells
export NVM_DIR="$HOME/.nvm"
if [[ -o interactive ]]; then
    # Set NPM_CONFIG_PREFIX only in interactive mode
    export NPM_CONFIG_PREFIX="$HOME/.npm-global"
    
    # Load NVM
    [ -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 "✅ Added clean agent optimization section"
echo ""
echo "🎉 Done! Now run:"
echo "   source ~/.zshrc"
echo "   zsh -lc 'echo test'  # Should have no warnings"
