#!/bin/bash
#
# ThrillWiki Quick Start Script
# One-command setup for bulletproof automation system
#
# Features:
# - Automated setup with sensible defaults for development
# - Minimal user interaction required
# - Rollback capabilities if setup fails
# - Clear status reporting and next steps
# - Support for different environment types (dev/prod)
#

set -e

# [AWS-SECRET-REMOVED]====================================
# SCRIPT CONFIGURATION
# [AWS-SECRET-REMOVED]====================================
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"
SCRIPT_NAME="$(basename "${BASH_SOURCE[0]}")"

# Quick start configuration
QUICK_START_LOG="$PROJECT_DIR/logs/quick-start.log"
ROLLBACK_FILE="$PROJECT_DIR/.quick-start-rollback"

# Setup scripts
SETUP_SCRIPT="$SCRIPT_DIR/setup-automation.sh"
GITHUB_SETUP_SCRIPT="$SCRIPT_DIR/github-setup.py"
CONFIG_LIB="$SCRIPT_DIR/automation-config.sh"

# Environment presets
declare -A ENV_PRESETS=(
    ["dev"]="Development environment with frequent updates"
    ["prod"]="Production environment with stable intervals"
    ["demo"]="Demo environment for testing and showcasing"
)

# Default configurations for each environment
declare -A DEV_CONFIG=(
    ["PULL_INTERVAL"]="60"           # 1 minute for development
    ["HEALTH_CHECK_INTERVAL"]="30"   # 30 seconds
    ["AUTO_MIGRATE"]="true"
    ["AUTO_UPDATE_DEPENDENCIES"]="true"
    ["DEBUG_MODE"]="true"
)

declare -A PROD_CONFIG=(
    ["PULL_INTERVAL"]="300"          # 5 minutes for production
    ["HEALTH_CHECK_INTERVAL"]="60"   # 1 minute
    ["AUTO_MIGRATE"]="true"
    ["AUTO_UPDATE_DEPENDENCIES"]="false"
    ["DEBUG_MODE"]="false"
)

declare -A DEMO_CONFIG=(
    ["PULL_INTERVAL"]="120"          # 2 minutes for demo
    ["HEALTH_CHECK_INTERVAL"]="45"   # 45 seconds
    ["AUTO_MIGRATE"]="true"
    ["AUTO_UPDATE_DEPENDENCIES"]="true"
    ["DEBUG_MODE"]="false"
)

# [AWS-SECRET-REMOVED]====================================
# COLOR DEFINITIONS
# [AWS-SECRET-REMOVED]====================================
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m' # No Color

# [AWS-SECRET-REMOVED]====================================
# LOGGING FUNCTIONS
# [AWS-SECRET-REMOVED]====================================

quick_log() {
    local level="$1"
    local color="$2"
    local message="$3"
    local timestamp="$(date '+%Y-%m-%d %H:%M:%S')"
    
    # Ensure log directory exists
    mkdir -p "$(dirname "$QUICK_START_LOG")"
    
    # Log to file (without colors)
    echo "[$timestamp] [$level] $message" >> "$QUICK_START_LOG"
    
    # Log to console (with colors)
    echo -e "${color}[$timestamp] [QUICK-$level]${NC} $message"
}

quick_info() {
    quick_log "INFO" "$BLUE" "$1"
}

quick_success() {
    quick_log "SUCCESS" "$GREEN" "✅ $1"
}

quick_warning() {
    quick_log "WARNING" "$YELLOW" "⚠️  $1"
}

quick_error() {
    quick_log "ERROR" "$RED" "❌ $1"
}

quick_debug() {
    if [[ "${QUICK_DEBUG:-false}" == "true" ]]; then
        quick_log "DEBUG" "$PURPLE" "🔍 $1"
    fi
}

# [AWS-SECRET-REMOVED]====================================
# UTILITY FUNCTIONS
# [AWS-SECRET-REMOVED]====================================

command_exists() {
    command -v "$1" >/dev/null 2>&1
}

# Show animated progress
show_spinner() {
    local pid="$1"
    local message="$2"
    local delay=0.1
    local spinstr='|/-\'
    
    while ps -p "$pid" >/dev/null 2>&1; do
        local temp=${spinstr#?}
        printf "\r%s %c" "$message" "$spinstr"
        local spinstr=$temp${spinstr%"$temp"}
        sleep $delay
    done
    printf "\r%s ✓\n" "$message"
}

# Check if we're in a supported environment
detect_environment() {
    quick_debug "Detecting environment type"
    
    # Check for common development indicators
    if [[ -f "$PROJECT_DIR/manage.py" ]] && [[ -d "$PROJECT_DIR/.git" ]]; then
        if [[ -f "$PROJECT_DIR/pyproject.toml" ]] || [[ -f "$PROJECT_DIR/requirements.txt" ]]; then
            echo "dev"
            return 0
        fi
    fi
    
    # Check for production indicators
    if [[ -d "/etc/systemd/system" ]] && [[ "$USER" != "root" ]]; then
        echo "prod"
        return 0
    fi
    
    # Default to development
    echo "dev"
}

# [AWS-SECRET-REMOVED]====================================
# ROLLBACK FUNCTIONALITY
# [AWS-SECRET-REMOVED]====================================

# Save rollback information
save_rollback_info() {
    local action="$1"
    local details="$2"
    
    quick_debug "Saving rollback info: $action"
    
    mkdir -p "$(dirname "$ROLLBACK_FILE")"
    echo "$(date '+%Y-%m-%d %H:%M:%S')|$action|$details" >> "$ROLLBACK_FILE"
}

# Perform rollback
perform_rollback() {
    quick_warning "Performing rollback of changes"
    
    if [[ ! -f "$ROLLBACK_FILE" ]]; then
        quick_info "No rollback information found"
        return 0
    fi
    
    local rollback_errors=0
    
    # Read rollback file in reverse order
    while IFS='|' read -r timestamp action details; do
        quick_debug "Rolling back: $action ($details)"
        
        case "$action" in
            "created_file")
                if [[ -f "$details" ]]; then
                    rm -f "$details" && quick_debug "Removed file: $details" || ((rollback_errors++))
                fi
                ;;
            "modified_file")
                # For modified files, we would need to restore from backup
                # This is a simplified rollback - in practice, you'd restore from backup
                quick_debug "File was modified: $details (manual restoration may be needed)"
                ;;
            "installed_service")
                if command_exists systemctl && [[ -f "/etc/systemd/system/$details" ]]; then
                    sudo systemctl stop "$details" 2>/dev/null || true
                    sudo systemctl disable "$details" 2>/dev/null || true
                    sudo rm -f "/etc/systemd/system/$details" && quick_debug "Removed service: $details" || ((rollback_errors++))
                    sudo systemctl daemon-reload 2>/dev/null || true
                fi
                ;;
            "created_directory")
                if [[ -d "$details" ]]; then
                    rmdir "$details" 2>/dev/null && quick_debug "Removed directory: $details" || quick_debug "Directory not empty: $details"
                fi
                ;;
        esac
    done < <(tac "$ROLLBACK_FILE" 2>/dev/null || cat "$ROLLBACK_FILE")
    
    # Remove rollback file
    rm -f "$ROLLBACK_FILE"
    
    if [[ $rollback_errors -eq 0 ]]; then
        quick_success "Rollback completed successfully"
    else
        quick_warning "Rollback completed with $rollback_errors errors"
        quick_info "Some manual cleanup may be required"
    fi
}

# [AWS-SECRET-REMOVED]====================================
# QUICK SETUP FUNCTIONS
# [AWS-SECRET-REMOVED]====================================

# Quick dependency check
quick_check_dependencies() {
    quick_info "Checking system dependencies"
    
    local missing_deps=()
    local required_deps=("git" "curl" "python3")
    
    for dep in "${required_deps[@]}"; do
        if ! command_exists "$dep"; then
            missing_deps+=("$dep")
        fi
    done
    
    # Check for UV specifically
    if ! command_exists "uv"; then
        missing_deps+=("uv (Python package manager)")
    fi
    
    if [[ ${#missing_deps[@]} -gt 0 ]]; then
        quick_error "Missing required dependencies: ${missing_deps[*]}"
        echo ""
        echo "🚀 Quick Installation Commands:"
        echo ""
        
        if command_exists apt-get; then
            echo "# Ubuntu/Debian:"
            echo "sudo apt-get update && sudo apt-get install -y git curl python3"
            echo "curl -LsSf https://astral.sh/uv/install.sh | sh"
        elif command_exists yum; then
            echo "# RHEL/CentOS:"
            echo "sudo yum install -y git curl python3"
            echo "curl -LsSf https://astral.sh/uv/install.sh | sh"
        elif command_exists brew; then
            echo "# macOS:"
            echo "brew install git curl python3"
            echo "curl -LsSf https://astral.sh/uv/install.sh | sh"
        fi
        
        echo ""
        echo "After installing dependencies, run this script again:"
        echo "  $0"
        
        return 1
    fi
    
    quick_success "All dependencies are available"
    return 0
}

# Apply environment preset configuration
apply_environment_preset() {
    local env_type="$1"
    
    quick_info "Applying $env_type environment configuration"
    
    # Load configuration library
    if [[ -f "$CONFIG_LIB" ]]; then
        # shellcheck source=automation-config.sh
        source "$CONFIG_LIB"
    else
        quick_error "Configuration library not found: $CONFIG_LIB"
        return 1
    fi
    
    # Get configuration for environment type
    local -n config_ref="${env_type^^}_CONFIG"
    
    # Apply each configuration value
    for key in "${!config_ref[@]}"; do
        local value="${config_ref[$key]}"
        quick_debug "Setting $key=$value"
        
        if declare -f write_config_value >/dev/null 2>&1; then
            write_config_value "$key" "$value"
        else
            quick_warning "Could not set configuration value: $key"
        fi
    done
    
    quick_success "Environment configuration applied"
}

# Quick GitHub setup (optional)
quick_github_setup() {
    local skip_github="${1:-false}"
    
    if [[ "$skip_github" == "true" ]]; then
        quick_info "Skipping GitHub authentication setup"
        return 0
    fi
    
    quick_info "Setting up GitHub authentication (optional)"
    echo ""
    echo "🔐 GitHub Personal Access Token Setup"
    echo "This enables private repository access and avoids rate limits."
    echo "You can skip this step and set it up later if needed."
    echo ""
    
    read -r -p "Do you want to set up GitHub authentication now? (Y/n): " setup_github
    
    if [[ "$setup_github" =~ ^[Nn] ]]; then
        quick_info "Skipping GitHub authentication - you can set it up later with:"
        echo "  python3 $GITHUB_SETUP_SCRIPT setup"
        return 0
    fi
    
    # Run GitHub setup with timeout
    if timeout 300 python3 "$GITHUB_SETUP_SCRIPT" setup; then
        quick_success "GitHub authentication configured"
        save_rollback_info "configured_github" "token"
        return 0
    else
        quick_warning "GitHub setup failed or timed out"
        quick_info "Continuing without GitHub authentication"
        return 0
    fi
}

# Quick service setup
quick_service_setup() {
    local enable_service="${1:-true}"
    
    if [[ "$enable_service" != "true" ]]; then
        quick_info "Skipping service installation"
        return 0
    fi
    
    if ! command_exists systemctl; then
        quick_info "systemd not available - skipping service setup"
        return 0
    fi
    
    quick_info "Setting up systemd service"
    
    # Use the main setup script for service installation
    if "$SETUP_SCRIPT" --force-rebuild service >/dev/null 2>&1; then
        quick_success "Systemd service installed"
        save_rollback_info "installed_service" "thrillwiki-automation.service"
        return 0
    else
        quick_warning "Service installation failed - continuing without systemd integration"
        return 0
    fi
}

# [AWS-SECRET-REMOVED]====================================
# MAIN QUICK START WORKFLOW
# [AWS-SECRET-REMOVED]====================================

run_quick_start() {
    local env_type="${1:-auto}"
    local skip_github="${2:-false}"
    local enable_service="${3:-true}"
    
    echo ""
    echo "🚀 ThrillWiki Quick Start"
    echo "========================="
    echo ""
    echo "This script will quickly set up the ThrillWiki automation system"
    echo "with sensible defaults for immediate use."
    echo ""
    
    # Auto-detect environment if not specified
    if [[ "$env_type" == "auto" ]]; then
        env_type=$(detect_environment)
        quick_info "Auto-detected environment type: $env_type"
    fi
    
    # Show environment preset info
    if [[ -n "${ENV_PRESETS[$env_type]}" ]]; then
        echo "📋 Environment: ${ENV_PRESETS[$env_type]}"
    else
        quick_warning "Unknown environment type: $env_type, using development defaults"
        env_type="dev"
    fi
    
    echo ""
    echo "⚡ Quick Setup Features:"
    echo "• Minimal user interaction"
    echo "• Automatic dependency validation"
    echo "• Environment-specific configuration"
    echo "• Optional GitHub authentication"
    echo "• Systemd service integration"
    echo "• Rollback support on failure"
    echo ""
    
    read -r -p "Continue with quick setup? (Y/n): " continue_setup
    if [[ "$continue_setup" =~ ^[Nn] ]]; then
        quick_info "Quick setup cancelled"
        echo ""
        echo "💡 For interactive setup with more options, run:"
        echo "  $SETUP_SCRIPT setup"
        exit 0
    fi
    
    # Clear any previous rollback info
    rm -f "$ROLLBACK_FILE"
    
    local start_time
    start_time=$(date +%s)
    
    echo ""
    echo "🔧 Starting quick setup..."
    
    # Step 1: Dependencies
    echo ""
    echo "[1/5] Checking dependencies..."
    if ! quick_check_dependencies; then
        exit 1
    fi
    
    # Step 2: Configuration
    echo ""
    echo "[2/5] Setting up configuration..."
    
    # Load and initialize configuration
    if [[ -f "$CONFIG_LIB" ]]; then
        # shellcheck source=automation-config.sh
        source "$CONFIG_LIB"
        
        if init_configuration >/dev/null 2>&1; then
            quick_success "Configuration initialized"
            save_rollback_info "modified_file" "$(dirname "$ENV_CONFIG")/thrillwiki-automation***REMOVED***"
        else
            quick_error "Configuration initialization failed"
            perform_rollback
            exit 1
        fi
    else
        quick_error "Configuration library not found"
        exit 1
    fi
    
    # Apply environment preset
    if apply_environment_preset "$env_type"; then
        quick_success "Environment configuration applied"
    else
        quick_warning "Environment configuration partially applied"
    fi
    
    # Step 3: GitHub Authentication (optional)
    echo ""
    echo "[3/5] GitHub authentication..."
    quick_github_setup "$skip_github"
    
    # Step 4: Service Installation
    echo ""
    echo "[4/5] Service installation..."
    quick_service_setup "$enable_service"
    
    # Step 5: Final Validation
    echo ""
    echo "[5/5] Validating setup..."
    
    # Quick validation
    local validation_errors=0
    
    # Check configuration
    if [[ -f "$(dirname "$ENV_CONFIG")/thrillwiki-automation***REMOVED***" ]]; then
        quick_success "✓ Configuration file created"
    else
        quick_error "✗ Configuration file missing"
        ((validation_errors++))
    fi
    
    # Check scripts
    if [[ -x "$SCRIPT_DIR/bulletproof-automation.sh" ]]; then
        quick_success "✓ Automation script is executable"
    else
        quick_warning "⚠ Automation script may need executable permissions"
    fi
    
    # Check GitHub auth (optional)
    if [[ -f "$PROJECT_DIR/.github-pat" ]]; then
        quick_success "✓ GitHub authentication configured"
    else
        quick_info "ℹ GitHub authentication not configured (optional)"
    fi
    
    # Check service (optional)
    if command_exists systemctl && systemctl list-unit-files thrillwiki-automation.service >/dev/null 2>&1; then
        quick_success "✓ Systemd service installed"
    else
        quick_info "ℹ Systemd service not installed (optional)"
    fi
    
    local end_time
    end_time=$(date +%s)
    local setup_duration=$((end_time - start_time))
    
    echo ""
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    
    if [[ $validation_errors -eq 0 ]]; then
        quick_success "🎉 Quick setup completed successfully in ${setup_duration}s!"
    else
        quick_warning "⚠️  Quick setup completed with warnings in ${setup_duration}s"
    fi
    
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    
    # Clean up rollback file on success
    if [[ $validation_errors -eq 0 ]]; then
        rm -f "$ROLLBACK_FILE"
    fi
    
    # Show next steps
    show_next_steps "$env_type"
}

show_next_steps() {
    local env_type="$1"
    
    echo ""
    echo "🎯 Next Steps:"
    echo ""
    
    echo "🚀 Start Automation:"
    if command_exists systemctl && systemctl list-unit-files thrillwiki-automation.service >/dev/null 2>&1; then
        echo "  sudo systemctl start thrillwiki-automation     # Start service"
        echo "  sudo systemctl enable thrillwiki-automation    # Enable auto-start"
        echo "  sudo systemctl status thrillwiki-automation    # Check status"
    else
        echo "  $SCRIPT_DIR/bulletproof-automation.sh          # Start manually"
        echo "  $SETUP_SCRIPT start                            # Alternative start"
    fi
    
    echo ""
    echo "📊 Monitor Automation:"
    if command_exists systemctl; then
        echo "  sudo journalctl -u thrillwiki-automation -f     # Follow logs"
    fi
    echo "  tail -f $QUICK_START_LOG                         # Quick start logs"
    echo "  $SETUP_SCRIPT status                             # Check status"
    
    echo ""
    echo "🔧 Manage Configuration:"
    echo "  $SETUP_SCRIPT setup                              # Interactive setup"
    echo "  python3 $GITHUB_SETUP_SCRIPT status              # GitHub auth status"
    echo "  $SETUP_SCRIPT restart                            # Restart automation"
    
    echo ""
    echo "📖 Environment: $env_type"
    case "$env_type" in
        "dev")
            echo "  • Pull interval: 1 minute (fast development)"
            echo "  • Auto-migrations enabled"
            echo "  • Debug mode enabled"
            ;;
        "prod")
            echo "  • Pull interval: 5 minutes (stable production)"
            echo "  • Auto-migrations enabled"
            echo "  • Debug mode disabled"
            ;;
        "demo")
            echo "  • Pull interval: 2 minutes (demo environment)"
            echo "  • Auto-migrations enabled"
            echo "  • Debug mode disabled"
            ;;
    esac
    
    echo ""
    echo "💡 Tips:"
    echo "  • Automation will start pulling changes automatically"
    echo "  • Django migrations run automatically on code changes"
    echo "  • Server restarts automatically when needed"
    echo "  • Logs are available via systemd journal or log files"
    
    if [[ ! -f "$PROJECT_DIR/.github-pat" ]]; then
        echo ""
        echo "🔐 Optional: Set up GitHub authentication later for private repos:"
        echo "  python3 $GITHUB_SETUP_SCRIPT setup"
    fi
}

# [AWS-SECRET-REMOVED]====================================
# COMMAND LINE INTERFACE
# [AWS-SECRET-REMOVED]====================================

show_quick_help() {
    echo "ThrillWiki Quick Start Script"
    echo "Usage: $SCRIPT_NAME [ENVIRONMENT] [OPTIONS]"
    echo ""
    echo "ENVIRONMENTS:"
    echo "  dev                      Development environment (default)"
    echo "  prod                     Production environment"
    echo "  demo                     Demo environment"
    echo "  auto                     Auto-detect environment"
    echo ""
    echo "OPTIONS:"
    echo "  --skip-github            Skip GitHub authentication setup"
    echo "  --no-service             Skip systemd service installation"
    echo "  --rollback               Rollback previous quick start changes"
    echo "  --debug                  Enable debug logging"
    echo "  --help                   Show this help"
    echo ""
    echo "EXAMPLES:"
    echo "  $SCRIPT_NAME                    # Quick start with auto-detection"
    echo "  $SCRIPT_NAME dev                # Development environment"
    echo "  $SCRIPT_NAME prod --skip-github # Production without GitHub"
    echo "  $SCRIPT_NAME --rollback         # Rollback previous setup"
    echo ""
    echo "ENVIRONMENT PRESETS:"
    for env in "${!ENV_PRESETS[@]}"; do
        echo "  $env: ${ENV_PRESETS[$env]}"
    done
    echo ""
}

main() {
    local env_type="auto"
    local skip_github="false"
    local enable_service="true"
    local show_help="false"
    local perform_rollback_only="false"
    
    # Parse arguments
    while [[ $# -gt 0 ]]; do
        case "$1" in
            dev|prod|demo|auto)
                env_type="$1"
                shift
                ;;
            --skip-github)
                skip_github="true"
                shift
                ;;
            --no-service)
                enable_service="false"
                shift
                ;;
            --rollback)
                perform_rollback_only="true"
                shift
                ;;
            --debug)
                export QUICK_DEBUG="true"
                shift
                ;;
            --help|-h)
                show_help="true"
                shift
                ;;
            *)
                quick_error "Unknown option: $1"
                show_quick_help
                exit 1
                ;;
        esac
    done
    
    if [[ "$show_help" == "true" ]]; then
        show_quick_help
        exit 0
    fi
    
    if [[ "$perform_rollback_only" == "true" ]]; then
        perform_rollback
        exit 0
    fi
    
    # Validate environment type
    if [[ "$env_type" != "auto" ]] && [[ -z "${ENV_PRESETS[$env_type]}" ]]; then
        quick_error "Invalid environment type: $env_type"
        show_quick_help
        exit 1
    fi
    
    # Run quick start
    run_quick_start "$env_type" "$skip_github" "$enable_service"
}

# Set up trap for cleanup on script exit
trap 'if [[ -f "$ROLLBACK_FILE" ]] && [[ $? -ne 0 ]]; then quick_error "Setup failed - performing rollback"; perform_rollback; fi' EXIT

# Run main function
main "$@"