#!/bin/bash
set -e

# MatDrupal MCP - Complete Uninstallation Script
# Created by Mathieu Boisvert

INSTALL_DIR="$HOME/.matdrupal"
COPILOT_CONFIG_DIR="$HOME/Library/Application Support/Code/User"
COPILOT_CONFIG_FILE="$COPILOT_CONFIG_DIR/mcp.json"
BACKUP_DIR="$HOME/.matdrupal-uninstall-backup-$(date +%Y%m%d-%H%M%S)"

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

echo -e "${BLUE}🗑️ MatDrupal MCP - Complete Uninstallation${NC}"
echo -e "${BLUE}   Created by Mathieu Boisvert (github.com/boisvertmath)${NC}"
echo ""

# Warning
echo -e "${YELLOW}⚠️  WARNING: This operation will completely remove MatDrupal MCP${NC}"
echo ""
echo "What will be removed:"
echo "   • Installation directory: $INSTALL_DIR"
echo "   • GitHub Copilot configuration (matdrupal server only)"
echo "   • Update scripts"
echo "   • Local configurations in projects"
echo ""
echo "What will be preserved:"
echo "   • Other MCP servers in GitHub Copilot"
echo "   • Custom project configurations"
echo "   • VS Code extensions"
echo ""

# Ask for confirmation
read -p "Are you sure you want to uninstall MatDrupal MCP? (y/N): " -n 1 -r
echo ""

if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo -e "${YELLOW}❌ Uninstallation cancelled${NC}"
    exit 0
fi

echo -e "${YELLOW}🔄 Starting uninstallation...${NC}"

# Create backup directory
mkdir -p "$BACKUP_DIR"
echo -e "${BLUE}📦 Backup created in: ${NC}$BACKUP_DIR"

# 1. Stop running MCP processes
echo -e "${YELLOW}⏹️ Stopping MatDrupal MCP processes...${NC}"
pkill -f "matdrupal" 2>/dev/null || true
pkill -f "mat-drupal-mcp" 2>/dev/null || true
sleep 2
echo -e "${GREEN}✅ Processes stopped${NC}"

# 2. Backup GitHub Copilot configuration
if [ -f "$COPILOT_CONFIG_FILE" ]; then
    echo -e "${YELLOW}💾 Backing up GitHub Copilot configuration...${NC}"
    cp "$COPILOT_CONFIG_FILE" "$BACKUP_DIR/mcp-config-backup.json"
    echo -e "${GREEN}✅ Configuration backed up${NC}"
fi

# 3. Remove MatDrupal from GitHub Copilot configuration
if [ -f "$COPILOT_CONFIG_FILE" ]; then
    echo -e "${YELLOW}🔧 Removing MatDrupal from GitHub Copilot configuration...${NC}"
    
    # Create Node.js script to clean configuration
    cat > /tmp/remove-matdrupal-config.js << 'EOF'
const fs = require('fs');
const path = require('path');
const os = require('os');

const configFile = path.join(os.homedir(), 'Library/Application Support/Code/User/mcp.json');

if (fs.existsSync(configFile)) {
  try {
    const config = JSON.parse(fs.readFileSync(configFile, 'utf8'));
    
    // Remove matdrupal configuration
    if (config.mcpServers && config.mcpServers.matdrupal) {
      delete config.mcpServers.matdrupal;
      console.log('MatDrupal configuration removed');
      
      // If no more MCP servers, remove mcpServers section
      if (Object.keys(config.mcpServers).length === 0) {
        delete config.mcpServers;
        console.log('Empty mcpServers section removed');
      }
      
      // If configuration is now empty, remove file
      if (Object.keys(config).length === 0) {
        fs.unlinkSync(configFile);
        console.log('Empty configuration file removed');
      } else {
        fs.writeFileSync(configFile, JSON.stringify(config, null, 2));
        console.log('Configuration updated');
      }
    } else {
      console.log('MatDrupal configuration not found');
    }
  } catch (error) {
    console.error('Error reading configuration:', error.message);
  }
} else {
  console.log('GitHub Copilot configuration file not found');
}
EOF

    # Execute cleanup script
    node /tmp/remove-matdrupal-config.js
    rm /tmp/remove-matdrupal-config.js
    
    echo -e "${GREEN}✅ GitHub Copilot configuration cleaned${NC}"
fi

# 4. Backup complete installation directory
if [ -d "$INSTALL_DIR" ]; then
    echo -e "${YELLOW}📁 Backing up installation directory...${NC}"
    cp -r "$INSTALL_DIR" "$BACKUP_DIR/matdrupal-installation"
    echo -e "${GREEN}✅ Installation backed up${NC}"
fi

# 5. Remove installation directory
if [ -d "$INSTALL_DIR" ]; then
    echo -e "${YELLOW}🗑️ Removing installation directory...${NC}"
    rm -rf "$INSTALL_DIR"
    echo -e "${GREEN}✅ Installation directory removed${NC}"
fi

# 6. Clean local configurations in projects
echo -e "${YELLOW}🧹 Cleaning local configurations...${NC}"

# Search and clean local MCP configuration files
CLEANED=0

for PROJECT_DIR in "$HOME/Projets" "$HOME/Projects" "$HOME/Sites" "$HOME/workspace" "$HOME/dev"; do
    if [ -d "$PROJECT_DIR" ]; then
        echo "Cleaning $PROJECT_DIR..."
        
        # Find and remove all .vscode/mcp-config.json files
        find "$PROJECT_DIR" -name "mcp-config.json" -path "*/.vscode/*" 2>/dev/null | while read -r config_file; do
            echo "   🗑️ Removing: $config_file"
            rm -f "$config_file"
            ((CLEANED++))
        done
        
        # Clean references in settings.json
        find "$PROJECT_DIR" -name "settings.json" -path "*/.vscode/*" 2>/dev/null | while read -r settings_file; do
            if grep -q "mcpSettings\|matdrupal" "$settings_file" 2>/dev/null; then
                echo "   🔧 Cleaning MCP references in: $settings_file"
                # Backup
                cp "$settings_file" "$settings_file.backup.$(date +%Y%m%d-%H%M%S)"
                
                # Remove MCP references with jq if available
                if command -v jq &> /dev/null; then
                    jq 'del(.["github.copilot.chat.experimental.mcpSettings"]) | del(.matdrupal)' "$settings_file" > "$settings_file.tmp" && mv "$settings_file.tmp" "$settings_file"
                fi
            fi
        done
    fi
done

echo -e "${GREEN}✅ Local configurations cleaned${NC}"

# 7. Remove aliases and shortcuts
echo -e "${YELLOW}🔗 Removing shortcuts...${NC}"

# Check and remove aliases in profile files
for PROFILE_FILE in "$HOME/.bashrc" "$HOME/.zshrc" "$HOME/.profile" "$HOME/.bash_profile"; do
    if [ -f "$PROFILE_FILE" ] && grep -q "matdrupal\|mat-drupal-mcp" "$PROFILE_FILE" 2>/dev/null; then
        echo "   🔧 Cleaning aliases in: $PROFILE_FILE"
        # Backup
        cp "$PROFILE_FILE" "$PROFILE_FILE.backup.$(date +%Y%m%d-%H%M%S)"
        
        # Remove lines containing matdrupal
        sed -i.bak '/matdrupal\|mat-drupal-mcp/d' "$PROFILE_FILE"
        rm -f "$PROFILE_FILE.bak"
    fi
done

echo -e "${GREEN}✅ Shortcuts removed${NC}"

# 8. Clean npm global cache if installed via npm
echo -e "${YELLOW}📦 Checking npm installation...${NC}"
if command -v npm &> /dev/null; then
    if npm list -g mat-drupal-mcp &> /dev/null; then
        echo -e "${YELLOW}📦 Uninstalling global npm package...${NC}"
        npm uninstall -g mat-drupal-mcp
        echo -e "${GREEN}✅ NPM package uninstalled${NC}"
    else
        echo -e "${BLUE}ℹ️ NPM package not installed globally${NC}"
    fi
fi

# 9. Check remaining processes
echo -e "${YELLOW}🔍 Checking for remaining processes...${NC}"
REMAINING_PROCESSES=$(ps aux | grep -v grep | grep -c "matdrupal\|mat-drupal-mcp" || true)
if [ "$REMAINING_PROCESSES" -gt 0 ]; then
    echo -e "${YELLOW}⚠️ $REMAINING_PROCESSES MatDrupal processes still running${NC}"
    echo "   Restart your terminal or system if necessary"
else
    echo -e "${GREEN}✅ No MatDrupal processes running${NC}"
fi

# Final summary
echo ""
echo -e "${GREEN}🎉 Uninstallation completed successfully!${NC}"
echo ""
echo -e "${BLUE}📊 Summary:${NC}"
echo "   ✅ Installation directory removed"
echo "   ✅ GitHub Copilot configuration cleaned"
echo "   ✅ Local configurations removed"
echo "   ✅ Shortcuts and aliases removed"
echo "   ✅ NPM package uninstalled (if applicable)"
echo ""
echo -e "${YELLOW}💾 Backup created in:${NC}"
echo "   $BACKUP_DIR"
echo ""
echo -e "${BLUE}📋 Next steps:${NC}"
echo "   1. Restart VS Code or PhpStorm"
echo "   2. Restart your terminal (optional)"
echo "   3. The @matdrupal command will no longer be available"
echo ""
echo -e "${YELLOW}🔄 To reinstall MatDrupal MCP:${NC}"
echo "   curl -sL https://raw.githubusercontent.com/boisvertmath/mat-drupal-mcp/main/scripts/install.sh | bash"
echo ""
echo -e "${BLUE}🆘 Support:${NC}"
echo "   • GitHub: https://github.com/boisvertmath/mat-drupal-mcp/issues"
echo "   • Backup preserved for restoration if needed"
echo ""
echo -e "${BLUE}Thank you for using MatDrupal MCP!${NC}"
echo -e "${BLUE}Created by Mathieu Boisvert - https://github.com/boisvertmath${NC}"
