#!/bin/bash

# Roo Superpowers NPM - Uninstall Script
# Safely removes superpowers installation with backup option

set -e  # Exit on error

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Configuration
ROO_DIR="${HOME}/.roo"
SUPERPOWERS_DIR="${ROO_DIR}/superpowers"
BACKUP_DIR="${ROO_DIR}/.backups/superpowers-uninstall-$(date +%Y%m%d-%H%M%S)"

# Logging functions
log_info() {
    echo -e "${GREEN}[UNINSTALL]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[UNINSTALL]${NC} $1"
}

log_error() {
    echo -e "${RED}[UNINSTALL]${NC} $1"
}

echo -e "${GREEN}=== Roo Superpowers Uninstaller ===${NC}"
echo ""

# Check if superpowers is installed
if [[ ! -d "${SUPERPOWERS_DIR}" ]]; then
    log_warn "Superpowers not found at ${SUPERPOWERS_DIR}"
    log_info "Nothing to uninstall"
    exit 0
fi

# Ask for confirmation
log_warn "This will remove superpowers from ${SUPERPOWERS_DIR}"
echo ""
read -p "Create backup before removing? (Y/n): " create_backup

if [[ ! "${create_backup}" =~ ^[Nn]$ ]]; then
    log_info "Creating backup at ${BACKUP_DIR}..."
    mkdir -p "$(dirname "${BACKUP_DIR}")"
    cp -r "${SUPERPOWERS_DIR}" "${BACKUP_DIR}"
    log_info "Backup complete"
fi

echo ""
read -p "Proceed with uninstallation? (y/N): " confirm

if [[ ! "${confirm}" =~ ^[Yy]$ ]]; then
    log_info "Uninstallation cancelled"
    exit 0
fi

# Remove superpowers
log_info "Removing superpowers..."
rm -rf "${SUPERPOWERS_DIR}"

# Clean up temp files
if [[ -d "${ROO_DIR}/.tmp" ]]; then
    log_info "Cleaning up temporary files..."
    rm -rf "${ROO_DIR}/.tmp"
fi

echo ""
log_info "✓ Superpowers uninstalled successfully"
echo ""

if [[ -d "${BACKUP_DIR}" ]]; then
    echo "Backup saved at: ${BACKUP_DIR}"
    echo "To restore: mv '${BACKUP_DIR}' '${SUPERPOWERS_DIR}'"
fi

echo ""
log_info "To reinstall, run: npm install @roocode/superpowers"
echo ""