#!/bin/bash

# Roo Superpowers NPM - Installation Script
# Pass-through installer that always pulls latest obra/superpowers

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"
UPSTREAM_REPO="https://github.com/obra/superpowers.git"
TEMP_DIR="${ROO_DIR}/.tmp"
BACKUP_DIR="${ROO_DIR}/.backups/superpowers-$(date +%Y%m%d-%H%M%S)"

# Parse command line arguments
MODE="install"
if [[ "$1" == "--update" ]]; then
    MODE="update"
elif [[ "$1" == "--repair" ]]; then
    MODE="repair"
fi

echo -e "${GREEN}=== Roo Superpowers Installer ===${NC}"
echo "Mode: ${MODE}"
echo ""

# Function to log messages
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

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

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

log_debug() {
    if [[ "${DEBUG}" == "1" ]]; then
        echo -e "${BLUE}[DEBUG]${NC} $1"
    fi
}

# Function to check prerequisites
check_prerequisites() {
    log_info "Checking prerequisites..."
    
    if ! command -v git &> /dev/null; then
        log_error "git is not installed. Please install git first."
        exit 1
    fi
    
    log_info "Prerequisites OK"
}

# Function to backup existing installation
backup_existing() {
    if [[ -d "${SUPERPOWERS_DIR}" ]]; then
        log_info "Backing up existing installation to ${BACKUP_DIR}..."
        mkdir -p "$(dirname "${BACKUP_DIR}")"
        cp -r "${SUPERPOWERS_DIR}" "${BACKUP_DIR}"
        log_info "Backup complete"
    fi
}

# Function to pull latest upstream
pull_latest() {
    log_info "Pulling latest obra/superpowers from GitHub..."
    
    # Clean temp directory completely (remove locks and partial clones)
    if [[ -d "${TEMP_DIR}/superpowers" ]]; then
        rm -rf "${TEMP_DIR}/superpowers"
    fi
    
    # Create fresh temp directory and clear macOS quarantine attributes
    mkdir -p "${TEMP_DIR}"
    xattr -d com.apple.quarantine "${TEMP_DIR}" 2>/dev/null || true
    
    # Clone fresh copy with error output
    if ! git clone --depth 1 "${UPSTREAM_REPO}" "${TEMP_DIR}/superpowers" 2>&1; then
        log_error "Failed to clone upstream repository"
        log_error "Check your internet connection and try again"
        exit 1
    fi
    
    if [[ ! -d "${TEMP_DIR}/superpowers" ]]; then
        log_error "Clone appeared to succeed but directory not found"
        exit 1
    fi
    
    log_info "Successfully pulled latest version"
}

# Function to install superpowers
install_superpowers() {
    log_info "Installing superpowers to ${SUPERPOWERS_DIR}..."
    
    # Create .roo directory if it doesn't exist
    mkdir -p "${ROO_DIR}"
    
    # Remove old installation if exists
    if [[ -d "${SUPERPOWERS_DIR}" ]]; then
        rm -rf "${SUPERPOWERS_DIR}"
    fi
    
    # Move from temp to final location
    mv "${TEMP_DIR}/superpowers" "${SUPERPOWERS_DIR}"
    
    # Clean up temp directory
    rm -rf "${TEMP_DIR}"
    
    log_info "Installation complete"
}

# Function to verify installation
verify_installation() {
    log_info "Verifying installation..."
    
    # Check that superpowers directory exists and has content
    if [[ ! -d "${SUPERPOWERS_DIR}" ]]; then
        log_error "Superpowers directory not found"
        return 1
    fi
    
    # Check for key directories (adapt to actual structure)
    local required_items=(
        "${SUPERPOWERS_DIR}/skills"
        "${SUPERPOWERS_DIR}/.codex"
    )
    
    local found_count=0
    for item in "${required_items[@]}"; do
        if [[ -e "${item}" ]]; then
            log_debug "Found ${item}"
            ((found_count++))
        else
            log_debug "Optional item ${item} not found"
        fi
    done
    
    if [[ ${found_count} -eq 0 ]]; then
        log_error "No expected directories found - installation may be corrupted"
        return 1
    fi
    
    # Check that we have some skills
    local skill_count=$(find "${SUPERPOWERS_DIR}/skills" -name "SKILL.md" -type f 2>/dev/null | wc -l | tr -d ' ')
    
    if [[ "${skill_count}" -gt 0 ]]; then
        log_info "Found ${skill_count} skills"
    else
        log_warn "No skills found, but installation appears valid"
    fi
    
    log_info "Installation verified successfully"
    return 0
}

# Function to apply enhancements
apply_enhancements() {
    log_info "Applying adaptive enhancements..."
    
    # Call the enhancement script
    local script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
    local enhancement_script="${script_dir}/../enhancements/apply.sh"
    
    if [[ -f "${enhancement_script}" ]]; then
        bash "${enhancement_script}" "${SUPERPOWERS_DIR}"
        
        if [[ $? -eq 0 ]]; then
            log_info "Enhancements applied successfully"
        else
            log_warn "Enhancements failed to apply, but core installation is intact"
            log_warn "Run 'npm run repair' to try enhancements again"
        fi
    else
        log_warn "Enhancement script not found - skipping enhancements"
        log_info "Core superpowers installation is functional"
    fi
}

# Function to show completion message
show_completion() {
    echo ""
    echo -e "${GREEN}=== Installation Complete ===${NC}"
    echo ""
    echo "Superpowers installed to: ${SUPERPOWERS_DIR}"
    echo ""
    echo "To use superpowers in Roo Code:"
    echo "1. Ensure your .roo/config.json includes:"
    echo '   "skillsDirectory": "~/.roo/superpowers/skills"'
    echo ""
    echo "2. Run 'npm run update' to pull latest upstream changes anytime"
    echo ""
    echo "For more information, see README.md"
    echo ""
}

# Main installation flow
main() {
    check_prerequisites
    backup_existing
    pull_latest
    install_superpowers
    
    if verify_installation; then
        apply_enhancements
        show_completion
    else
        log_error "Installation verification failed"
        log_error "Backup available at: ${BACKUP_DIR}"
        exit 1
    fi
}

# Run main function
main