#!/bin/bash
#
# ThrillWiki Automation Setup Script
# Interactive setup for the bulletproof automation system
#
# Features:
# - Guided setup process with validation
# - GitHub PAT configuration and testing
# - Systemd service installation and configuration
# - Comprehensive error handling and rollback
# - Easy enable/disable/status commands
# - Configuration validation and testing
#

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]}")"

# Non-interactive mode flag
NON_INTERACTIVE=${NON_INTERACTIVE:-false}

# Load configuration library
CONFIG_LIB="$SCRIPT_DIR/automation-config.sh"
if [[ -f "$CONFIG_LIB" ]]; then
    # shellcheck source=automation-config.sh
    source "$CONFIG_LIB"
else
    echo "❌ Error: Configuration library not found: $CONFIG_LIB"
    exit 1
fi

# Setup scripts
GITHUB_SETUP_SCRIPT="$SCRIPT_DIR/github-setup.py"
BULLETPROOF_SCRIPT="$SCRIPT_DIR/bulletproof-automation.sh"

# Systemd configuration
SYSTEMD_DIR="$PROJECT_DIR/scripts/systemd"
SETUP_SERVICE_FILE="$SYSTEMD_DIR/thrillwiki-automation.service"
ENV_EXAMPLE="$SYSTEMD_DIR/thrillwiki-automation***REMOVED***.example"
ENV_CONFIG="$SYSTEMD_DIR/thrillwiki-automation***REMOVED***"

# Installation paths
SYSTEM_SERVICE_DIR="/etc/systemd/system"
SYSTEM_SERVICE_FILE="$SYSTEM_SERVICE_DIR/thrillwiki-automation.service"

# [AWS-SECRET-REMOVED]====================================
# SETUP STATE TRACKING
# [AWS-SECRET-REMOVED]====================================
SETUP_LOG="$PROJECT_DIR/logs/setup-automation.log"
SETUP_STATE_FILE="$PROJECT_DIR/.automation-setup-state"

# Setup steps
declare -A SETUP_STEPS=(
    ["dependencies"]="Validate dependencies"
    ["github"]="Configure GitHub authentication"
    ["configuration"]="Set up configuration files"
    ["service"]="Install systemd service"
    ["validation"]="Validate complete setup"
)

# [AWS-SECRET-REMOVED]====================================
# LOGGING AND UI
# [AWS-SECRET-REMOVED]====================================

setup_log() {
    local level="$1"
    local message="$2"
    local timestamp="$(date '+%Y-%m-%d %H:%M:%S')"
    
    # Ensure log directory exists
    mkdir -p "$(dirname "$SETUP_LOG")"
    
    # Log to file
    echo "[$timestamp] [$level] $message" >> "$SETUP_LOG"
    
    # Also use config library logging if available
    if declare -f config_log >/dev/null 2>&1; then
        case "$level" in
            "INFO") config_info "$message" ;;
            "SUCCESS") config_success "$message" ;;
            "WARNING") config_warning "$message" ;;
            "ERROR") config_error "$message" ;;
            "DEBUG") config_debug "$message" ;;
        esac
    else
        echo "[$level] $message"
    fi
}

setup_info() { setup_log "INFO" "$1"; }
setup_success() { setup_log "SUCCESS" "$1"; }
setup_warning() { setup_log "WARNING" "$1"; }
setup_error() { setup_log "ERROR" "$1"; }
setup_debug() { setup_log "DEBUG" "$1"; }

# Non-interactive prompt helper
non_interactive_prompt() {
    local prompt_text="$1"
    local default_value="$2"
    local var_name="$3"
    
    if [[ "$NON_INTERACTIVE" == "true" ]]; then
        setup_info "Non-interactive mode: $prompt_text - using default: $default_value"
        eval "$var_name=\"$default_value\""
    else
        read -r -p "$prompt_text" "$var_name"
        eval "$var_name=\"\${$var_name:-$default_value}\""
    fi
}

# Progress indicator
show_progress() {
    local current="$1"
    local total="$2"
    local step_name="$3"
    
    echo ""
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo "🚀 ThrillWiki Automation Setup - Step $current of $total"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo "📋 Current Step: $step_name"
    
    # Progress bar
    local progress=$((current * 50 / total))
    local bar=""
    for ((i=0; i<progress; i++)); do bar+="█"; done
    for ((i=progress; i<50; i++)); do bar+="░"; done
    echo "Progress: [$bar] $current/$total"
    echo ""
}

# [AWS-SECRET-REMOVED]====================================
# STATE MANAGEMENT
# [AWS-SECRET-REMOVED]====================================

save_setup_state() {
    local step="$1"
    local status="$2"  # completed, failed, skipped
    
    setup_debug "Saving setup state: $step = $status"
    
    mkdir -p "$(dirname "$SETUP_STATE_FILE")"
    
    # Read existing state
    local temp_file
    temp_file=$(mktemp)
    
    if [[ -f "$SETUP_STATE_FILE" ]]; then
        # Remove existing entry for this step
        grep -v "^$step=" "$SETUP_STATE_FILE" > "$temp_file" || true
    fi
    
    # Add new entry
    echo "$step=$status" >> "$temp_file"
    
    # Save back
    mv "$temp_file" "$SETUP_STATE_FILE"
    chmod 600 "$SETUP_STATE_FILE"
}

get_setup_state() {
    local step="$1"
    
    if [[ -f "$SETUP_STATE_FILE" ]]; then
        grep "^$step=" "$SETUP_STATE_FILE" 2>/dev/null | cut -d'=' -f2 || echo "pending"
    else
        echo "pending"
    fi
}

clear_setup_state() {
    setup_debug "Clearing setup state"
    rm -f "$SETUP_STATE_FILE"
}

# [AWS-SECRET-REMOVED]====================================
# DEPENDENCY VALIDATION
# [AWS-SECRET-REMOVED]====================================

validate_dependencies() {
    setup_info "Validating system dependencies"
    
    local missing_deps=()
    local missing_optional=()
    
    # Required dependencies
    local required_deps=("git" "curl" "uv" "python3")
    for dep in "${required_deps[@]}"; do
        if ! command_exists "$dep"; then
            missing_deps+=("$dep")
        else
            setup_debug "Found required dependency: $dep"
        fi
    done
    
    # Optional dependencies
    local optional_deps=("systemctl" "lsof")
    for dep in "${optional_deps[@]}"; do
        if ! command_exists "$dep"; then
            missing_optional+=("$dep")
        else
            setup_debug "Found optional dependency: $dep"
        fi
    done
    
    # Check for systemd
    local has_systemd=false
    if command_exists systemctl && [[ -d "/etc/systemd/system" ]]; then
        has_systemd=true
        setup_debug "systemd is available"
    else
        setup_warning "systemd is not available - service installation will be skipped"
    fi
    
    # Report missing dependencies
    if [[ ${#missing_deps[@]} -gt 0 ]]; then
        setup_error "Missing required dependencies: ${missing_deps[*]}"
        echo ""
        echo "📦 Installation instructions:"
        echo ""
        
        # Provide installation instructions based on system
        if command_exists apt-get; then
            echo "Ubuntu/Debian:"
            echo "  sudo apt-get update"
            echo "  sudo apt-get install git curl python3"
            echo ""
            echo "UV (Python package manager):"
            echo "  curl -LsSf https://astral.sh/uv/install.sh | sh"
        elif command_exists yum; then
            echo "RHEL/CentOS:"
            echo "  sudo yum install git curl python3"
            echo ""
            echo "UV (Python package manager):"
            echo "  curl -LsSf https://astral.sh/uv/install.sh | sh"
        elif command_exists brew; then
            echo "macOS (Homebrew):"
            echo "  brew install git curl python3"
            echo "  curl -LsSf https://astral.sh/uv/install.sh | sh"
        else
            echo "Please install the missing dependencies for your system"
        fi
        
        echo ""
        echo "After installing dependencies, run this script again."
        return 1
    fi
    
    if [[ ${#missing_optional[@]} -gt 0 ]]; then
        setup_warning "Missing optional dependencies: ${missing_optional[*]}"
        setup_info "Some features may not be available"
    fi
    
    # Check project structure
    setup_debug "Validating project structure"
    
    if [[ ! -d "$PROJECT_DIR/.git" ]]; then
        setup_error "Not a Git repository: $PROJECT_DIR"
        return 1
    fi
    
    if [[ ! -f "$BULLETPROOF_SCRIPT" ]]; then
        setup_error "Bulletproof automation script not found: $BULLETPROOF_SCRIPT"
        return 1
    fi
    
    if [[ ! -f "$GITHUB_SETUP_SCRIPT" ]]; then
        setup_error "GitHub setup script not found: $GITHUB_SETUP_SCRIPT"
        return 1
    fi
    
    setup_success "All dependencies validated successfully"
    return 0
}

# [AWS-SECRET-REMOVED]====================================
# GITHUB AUTHENTICATION SETUP
# [AWS-SECRET-REMOVED]====================================

setup_github_authentication() {
    setup_info "Setting up GitHub authentication"
    
    # Check if GitHub token already exists and is valid
    if load_github_token >/dev/null 2>&1; then
        setup_success "Valid GitHub token already configured"
        
        if [[ "$NON_INTERACTIVE" == "true" ]]; then
            setup_info "Non-interactive mode: keeping existing GitHub configuration"
            return 0
        fi
        
        # Ask if user wants to reconfigure
        echo ""
        echo "🔐 GitHub authentication is already set up and working."
        read -r -p "Do you want to reconfigure it? (y/N): " reconfigure
        
        if [[ "$reconfigure" =~ ^[Yy] ]]; then
            setup_info "Reconfiguring GitHub authentication"
        else
            setup_info "Keeping existing GitHub configuration"
            return 0
        fi
    fi
    
    # Run GitHub setup script
    echo ""
    echo "🔐 Setting up GitHub Personal Access Token (PAT)"
    echo "This enables secure access to your GitHub repository for automation."
    echo ""
    
    if python3 "$GITHUB_SETUP_SCRIPT" setup; then
        setup_success "GitHub authentication configured successfully"
        return 0
    else
        setup_error "GitHub authentication setup failed"
        
        if [[ "$NON_INTERACTIVE" == "true" ]]; then
            setup_warning "Non-interactive mode: skipping GitHub authentication"
            return 0
        fi
        
        echo ""
        echo "📋 You can:"
        echo "1. Skip GitHub setup for now (automation will work with public repos)"
        echo "2. Try again with a different token"
        echo "3. Exit and manually configure authentication"
        echo ""
        
        read -r -p "What would you like to do? (skip/retry/exit): " choice
        case "$choice" in
            skip|s)
                setup_warning "GitHub authentication skipped"
                return 0
                ;;
            retry|r)
                return 1  # Will cause step to retry
                ;;
            exit|e|*)
                setup_info "Setup cancelled by user"
                exit 1
                ;;
        esac
    fi
}

# [AWS-SECRET-REMOVED]====================================
# CONFIGURATION FILE SETUP
# [AWS-SECRET-REMOVED]====================================

setup_configuration_files() {
    setup_info "Setting up configuration files"
    
    # Initialize configuration system
    if ! init_configuration; then
        setup_error "Failed to initialize configuration system"
        return 1
    fi
    
    # Create environment configuration if it doesn't exist
    if [[ ! -f "$ENV_CONFIG" ]]; then
        if [[ -f "$ENV_EXAMPLE" ]]; then
            setup_info "Creating environment configuration from template"
            cp "$ENV_EXAMPLE" "$ENV_CONFIG"
            chmod 600 "$ENV_CONFIG"
        else
            setup_error "Environment configuration template not found: $ENV_EXAMPLE"
            return 1
        fi
    fi
    
    # Configure basic settings
    setup_info "Configuring automation settings"
    
    # Set project directory
    write_config_value "PROJECT_DIR" "$PROJECT_DIR" "$ENV_CONFIG"
    
    # Configure default intervals
    if [[ "$NON_INTERACTIVE" != "true" ]]; then
        echo ""
        echo "⏱️  Automation Timing Configuration"
        echo "Configure how often the automation system checks for updates."
        echo ""
    fi
    
    # Pull interval
    local current_interval
    current_interval=$(read_config_value "PULL_INTERVAL" "$ENV_CONFIG" "300")
    
    if [[ "$NON_INTERACTIVE" == "true" ]]; then
        local pull_interval="$current_interval"
        setup_info "Non-interactive mode: using default pull interval: $pull_interval seconds"
    else
        echo "Current pull interval: $current_interval seconds ($(($current_interval / 60)) minutes)"
        read -r -p "Pull interval in seconds (default: $current_interval): " pull_interval
        pull_interval="${pull_interval:-$current_interval}"
    fi
    
    if [[ "$pull_interval" =~ ^[0-9]+$ ]] && [[ "$pull_interval" -ge 60 ]]; then
        write_config_value "PULL_INTERVAL" "$pull_interval" "$ENV_CONFIG"
        setup_debug "Set pull interval: $pull_interval seconds"
    else
        setup_warning "Invalid pull interval, keeping default: $current_interval"
    fi
    
    # Health check interval
    local current_health
    current_health=$(read_config_value "HEALTH_CHECK_INTERVAL" "$ENV_CONFIG" "60")
    
    if [[ "$NON_INTERACTIVE" == "true" ]]; then
        local health_interval="$current_health"
        setup_info "Non-interactive mode: using default health check interval: $health_interval seconds"
    else
        read -r -p "Health check interval in seconds (default: $current_health): " health_interval
        health_interval="${health_interval:-$current_health}"
    fi
    
    if [[ "$health_interval" =~ ^[0-9]+$ ]] && [[ "$health_interval" -ge 30 ]]; then
        write_config_value "HEALTH_CHECK_INTERVAL" "$health_interval" "$ENV_CONFIG"
        setup_debug "Set health check interval: $health_interval seconds"
    else
        setup_warning "Invalid health check interval, keeping default: $current_health"
    fi
    
    # Validate configuration
    if validate_config_file "$ENV_CONFIG"; then
        setup_success "Configuration files set up successfully"
        return 0
    else
        setup_error "Configuration validation failed"
        return 1
    fi
}

# [AWS-SECRET-REMOVED]====================================
# SYSTEMD SERVICE INSTALLATION
# [AWS-SECRET-REMOVED]====================================

install_systemd_service() {
    setup_info "Installing systemd service"
    
    # Check if systemd is available
    if ! command_exists systemctl; then
        setup_warning "systemd not available - skipping service installation"
        return 0
    fi
    
    if [[ ! -d "/etc/systemd/system" ]]; then
        setup_warning "systemd system directory not found - skipping service installation"
        return 0
    fi
    
    # Check for sudo/root access
    if [[ $EUID -ne 0 ]] && ! sudo -n true 2>/dev/null; then
        if [[ "$NON_INTERACTIVE" == "true" ]]; then
            setup_info "Non-interactive mode: proceeding with systemd service installation"
        else
            echo ""
            echo "🔐 Administrator access required to install systemd service"
            echo "The service will be installed to: $SYSTEM_SERVICE_FILE"
            echo ""
            
            read -r -p "Do you want to install the systemd service? (Y/n): " install_service
            if [[ "$install_service" =~ ^[Nn] ]]; then
                setup_info "Systemd service installation skipped"
                return 0
            fi
        fi
    fi
    
    # Check if service file exists
    if [[ ! -f "$SETUP_SERVICE_FILE" ]]; then
        setup_error "Service file not found: $SETUP_SERVICE_FILE"
        return 1
    fi
    
    # Update service file with current paths
    local temp_service
    temp_service=$(mktemp)
    
    # Replace placeholder paths with actual paths
    sed -e "s|/home/ubuntu/thrillwiki|$PROJECT_DIR|g" \
        -e "s|User=ubuntu|User=$(whoami)|g" \
        -e "s|Group=ubuntu|Group=$(id -gn)|g" \
        "$SETUP_SERVICE_FILE" > "$temp_service"
    
    # Install service file
    setup_debug "Installing service file to: $SYSTEM_SERVICE_FILE"
    
    if sudo cp "$temp_service" "$SYSTEM_SERVICE_FILE"; then
        rm -f "$temp_service"
        setup_debug "Service file installed successfully"
    else
        rm -f "$temp_service"
        setup_error "Failed to install service file"
        return 1
    fi
    
    # Set proper permissions
    sudo chmod 644 "$SYSTEM_SERVICE_FILE"
    
    # Reload systemd
    setup_debug "Reloading systemd daemon"
    if sudo systemctl daemon-reload; then
        setup_debug "systemd daemon reloaded"
    else
        setup_error "Failed to reload systemd daemon"
        return 1
    fi
    
    # Ask about enabling the service
    if [[ "$NON_INTERACTIVE" == "true" ]]; then
        local service_option="1"
        setup_info "Non-interactive mode: enabling service for auto-start"
    else
        echo ""
        echo "🚀 Service Installation Options"
        echo "1. Enable service (auto-start on boot)"
        echo "2. Install only (manual start)"
        echo ""
        
        read -r -p "Choose option (1/2, default: 1): " service_option
        service_option="${service_option:-1}"
    fi
    
    case "$service_option" in
        1)
            setup_info "Enabling service for auto-start"
            if sudo systemctl enable thrillwiki-automation; then
                setup_success "Service enabled for auto-start"
            else
                setup_error "Failed to enable service"
                return 1
            fi
            ;;
        2)
            setup_info "Service installed but not enabled"
            ;;
        *)
            setup_warning "Invalid option, service installed but not enabled"
            ;;
    esac
    
    setup_success "Systemd service installed successfully"
    return 0
}

# [AWS-SECRET-REMOVED]====================================
# FINAL VALIDATION
# [AWS-SECRET-REMOVED]====================================

validate_complete_setup() {
    setup_info "Validating complete automation setup"
    
    local validation_errors=0
    
    echo ""
    echo "🔍 Running comprehensive validation..."
    echo ""
    
    # Check configuration files
    setup_debug "Validating configuration files"
    if [[ -f "$ENV_CONFIG" ]]; then
        if validate_config_file "$ENV_CONFIG"; then
            setup_success "✓ Configuration file is valid"
        else
            setup_error "✗ Configuration file validation failed"
            ((validation_errors++))
        fi
    else
        setup_error "✗ Configuration file not found"
        ((validation_errors++))
    fi
    
    # Check GitHub authentication
    setup_debug "Validating GitHub authentication"
    if load_github_token >/dev/null 2>&1; then
        setup_success "✓ GitHub authentication is configured and valid"
    else
        setup_warning "⚠ GitHub authentication not configured (will use public access)"
    fi
    
    # Check systemd service
    setup_debug "Validating systemd service"
    if command_exists systemctl; then
        if [[ -f "$SYSTEM_SERVICE_FILE" ]]; then
            if systemctl is-enabled thrillwiki-automation >/dev/null 2>&1; then
                setup_success "✓ Systemd service is installed and enabled"
            else
                setup_info "ℹ Systemd service is installed but not enabled"
            fi
        else
            setup_warning "⚠ Systemd service not installed"
        fi
    else
        setup_info "ℹ systemd not available"
    fi
    
    # Check bulletproof script
    setup_debug "Validating bulletproof automation script"
    if [[ -x "$BULLETPROOF_SCRIPT" ]]; then
        setup_success "✓ Bulletproof automation script is executable"
    else
        setup_error "✗ Bulletproof automation script is not executable"
        ((validation_errors++))
    fi
    
    # Test automation script (dry run)
    setup_debug "Testing automation script"
    echo ""
    echo "🧪 Testing automation script (this may take a moment)..."
    
    if timeout 30 "$BULLETPROOF_SCRIPT" --validate-only 2>/dev/null; then
        setup_success "✓ Automation script validation passed"
    else
        setup_warning "⚠ Automation script validation failed or timed out"
        setup_info "This may be normal if the script requires network access"
    fi
    
    # Summary
    echo ""
    echo "📊 Validation Summary:"
    if [[ $validation_errors -eq 0 ]]; then
        setup_success "All critical validations passed!"
        echo ""
        echo "🎉 Setup completed successfully!"
        return 0
    else
        setup_error "$validation_errors critical validation(s) failed"
        echo ""
        echo "⚠️  Setup completed with warnings - please review the issues above"
        return 1
    fi
}

# [AWS-SECRET-REMOVED]====================================
# MAIN SETUP WORKFLOW
# [AWS-SECRET-REMOVED]====================================

run_interactive_setup() {
    setup_info "Starting ThrillWiki automation setup"
    
    if [[ "$NON_INTERACTIVE" != "true" ]]; then
        echo ""
        echo "🚀 ThrillWiki Bulletproof Automation Setup"
        echo "[AWS-SECRET-REMOVED]=="
        echo ""
        echo "This script will guide you through setting up the automated"
        echo "development environment for ThrillWiki with the following features:"
        echo ""
        echo "• 🔄 Automated Git repository pulls"
        echo "• 🐍 Automatic Django migrations and dependency updates"
        echo "• 🔐 Secure GitHub PAT authentication"
        echo "• ⚙️  Systemd service integration"
        echo "• 📊 Comprehensive logging and monitoring"
        echo ""
        
        read -r -p "Do you want to continue with the setup? (Y/n): " continue_setup
        if [[ "$continue_setup" =~ ^[Nn] ]]; then
            setup_info "Setup cancelled by user"
            exit 0
        fi
    else
        setup_info "Non-interactive mode: proceeding with automated setup"
    fi
    
    # Clear any previous setup state
    clear_setup_state
    
    local step_count=0
    local total_steps=${#SETUP_STEPS[@]}
    
    # Run setup steps
    for step in dependencies github configuration service validation; do
        ((step_count++))
        
        local step_name="${SETUP_STEPS[$step]}"
        local step_status
        step_status=$(get_setup_state "$step")
        
        # Skip completed steps unless forced
        if [[ "$step_status" == "completed" ]] && [[ "${FORCE_REBUILD:-false}" != "true" ]]; then
            setup_info "Step '$step_name' already completed - skipping"
            continue
        fi
        
        show_progress "$step_count" "$total_steps" "$step_name"
        
        local retry_count=0
        local max_retries=3
        
        while [[ $retry_count -lt $max_retries ]]; do
            case "$step" in
                dependencies)
                    if validate_dependencies; then
                        save_setup_state "$step" "completed"
                        break
                    else
                        save_setup_state "$step" "failed"
                        setup_error "Dependencies validation failed"
                        exit 1
                    fi
                    ;;
                    
                github)
                    if setup_github_authentication; then
                        save_setup_state "$step" "completed"
                        break
                    else
                        ((retry_count++))
                        if [[ $retry_count -lt $max_retries ]]; then
                            setup_warning "Retrying GitHub setup (attempt $((retry_count + 1))/$max_retries)"
                            sleep 2
                        else
                            save_setup_state "$step" "failed"
                            setup_error "GitHub setup failed after $max_retries attempts"
                            
                            if [[ "$NON_INTERACTIVE" == "true" ]]; then
                                setup_warning "Non-interactive mode: continuing without GitHub authentication"
                                save_setup_state "$step" "skipped"
                                break
                            else
                                read -r -p "Continue without GitHub authentication? (y/N): " continue_without_github
                                if [[ "$continue_without_github" =~ ^[Yy] ]]; then
                                    save_setup_state "$step" "skipped"
                                    break
                                else
                                    exit 1
                                fi
                            fi
                        fi
                    fi
                    ;;
                    
                configuration)
                    if setup_configuration_files; then
                        save_setup_state "$step" "completed"
                        break
                    else
                        ((retry_count++))
                        if [[ $retry_count -lt $max_retries ]]; then
                            setup_warning "Retrying configuration setup (attempt $((retry_count + 1))/$max_retries)"
                            sleep 2
                        else
                            save_setup_state "$step" "failed"
                            setup_error "Configuration setup failed after $max_retries attempts"
                            exit 1
                        fi
                    fi
                    ;;
                    
                service)
                    if install_systemd_service; then
                        save_setup_state "$step" "completed"
                        break
                    else
                        save_setup_state "$step" "failed"
                        setup_warning "Service installation failed - continuing without systemd integration"
                        break
                    fi
                    ;;
                    
                validation)
                    if validate_complete_setup; then
                        save_setup_state "$step" "completed"
                        break
                    else
                        save_setup_state "$step" "failed"
                        setup_warning "Validation completed with warnings"
                        break
                    fi
                    ;;
            esac
        done
    done
    
    # Final summary
    echo ""
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo "🎊 ThrillWiki Automation Setup Complete!"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo ""
    
    echo "📋 Next Steps:"
    echo ""
    
    # Show management commands
    echo "🎮 Management Commands:"
    echo "  $SCRIPT_NAME start     # Start automation service"
    echo "  $SCRIPT_NAME stop      # Stop automation service"
    echo "  $SCRIPT_NAME status    # Show service status"
    echo "  $SCRIPT_NAME restart   # Restart automation service"
    echo "  $SCRIPT_NAME logs      # Show service logs"
    echo ""
    
    echo "🔧 Manual Testing:"
    echo "  $BULLETPROOF_SCRIPT --help        # Show automation options"
    echo "  python3 $GITHUB_SETUP_SCRIPT status  # Check GitHub auth"
    echo ""
    
    echo "📊 Monitoring:"
    if command_exists systemctl && [[ -f "$SYSTEM_SERVICE_FILE" ]]; then
        echo "  sudo journalctl -u thrillwiki-automation -f  # Follow logs"
        echo "  sudo systemctl status thrillwiki-automation   # Service status"
    fi
    echo "  tail -f $SETUP_LOG  # Setup logs"
    echo ""
    
    setup_success "Setup completed! The automation system is ready to use."
}

# [AWS-SECRET-REMOVED]====================================
# SERVICE MANAGEMENT COMMANDS
# [AWS-SECRET-REMOVED]====================================

service_start() {
    setup_info "Starting ThrillWiki automation service"
    
    if command_exists systemctl && [[ -f "$SYSTEM_SERVICE_FILE" ]]; then
        if sudo systemctl start thrillwiki-automation; then
            setup_success "Service started successfully"
            sudo systemctl status thrillwiki-automation --no-pager
        else
            setup_error "Failed to start service"
            return 1
        fi
    else
        setup_info "Starting automation manually"
        "$BULLETPROOF_SCRIPT" &
        setup_success "Automation started in background"
    fi
}

service_stop() {
    setup_info "Stopping ThrillWiki automation service"
    
    if command_exists systemctl && [[ -f "$SYSTEM_SERVICE_FILE" ]]; then
        if sudo systemctl stop thrillwiki-automation; then
            setup_success "Service stopped successfully"
        else
            setup_error "Failed to stop service"
            return 1
        fi
    else
        setup_info "Stopping manual automation processes"
        pkill -f "bulletproof-automation.sh" || true
        setup_success "Automation processes stopped"
    fi
}

service_restart() {
    setup_info "Restarting ThrillWiki automation service"
    
    service_stop
    sleep 2
    service_start
}

service_status() {
    setup_info "Checking ThrillWiki automation status"
    
    echo ""
    echo "📊 Service Status:"
    
    if command_exists systemctl && [[ -f "$SYSTEM_SERVICE_FILE" ]]; then
        local status
        status=$(systemctl is-active thrillwiki-automation 2>/dev/null || echo "inactive")
        
        case "$status" in
            active)
                setup_success "✓ Service is running"
                sudo systemctl status thrillwiki-automation --no-pager
                ;;
            inactive)
                setup_warning "⚠ Service is stopped"
                ;;
            failed)
                setup_error "✗ Service has failed"
                sudo systemctl status thrillwiki-automation --no-pager
                ;;
            *)
                setup_info "ℹ Service status: $status"
                ;;
        esac
    else
        setup_info "ℹ No systemd service configured"
        
        # Check for manual processes
        if pgrep -f "bulletproof-automation.sh" >/dev/null; then
            setup_success "✓ Manual automation process is running"
        else
            setup_warning "⚠ No automation processes found"
        fi
    fi
    
    echo ""
    echo "🔐 GitHub Authentication:"
    if load_github_token >/dev/null 2>&1; then
        setup_success "✓ Valid GitHub token configured"
    else
        setup_warning "⚠ No valid GitHub token found"
    fi
    
    echo ""
    echo "📁 Configuration:"
    if [[ -f "$ENV_CONFIG" ]]; then
        setup_success "✓ Configuration file exists: $ENV_CONFIG"
    else
        setup_error "✗ Configuration file missing: $ENV_CONFIG"
    fi
}

service_logs() {
    setup_info "Showing ThrillWiki automation logs"
    
    if command_exists systemctl && [[ -f "$SYSTEM_SERVICE_FILE" ]]; then
        echo "📋 Following systemd service logs (Ctrl+C to exit):"
        sudo journalctl -u thrillwiki-automation -f
    else
        echo "📋 Following setup logs (Ctrl+C to exit):"
        tail -f "$SETUP_LOG"
    fi
}

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

show_help() {
    echo "ThrillWiki Automation Setup Script"
    echo "Usage: $SCRIPT_NAME [COMMAND] [OPTIONS]"
    echo ""
    echo "COMMANDS:"
    echo "  setup                    Run interactive setup process"
    echo "  start                    Start automation service"
    echo "  stop                     Stop automation service"
    echo "  restart                  Restart automation service"
    echo "  status                   Show service status"
    echo "  logs                     Show/follow service logs"
    echo "  validate                 Validate current setup"
    echo "  help                     Show this help"
    echo ""
    echo "OPTIONS:"
    echo "  --non-interactive        Run setup without user prompts (use defaults)"
    echo "  --force-rebuild          Force rebuild of all setup steps"
    echo "  --debug                  Enable debug logging"
    echo ""
    echo "EXAMPLES:"
    echo "  $SCRIPT_NAME setup                     # Interactive setup"
    echo "  $SCRIPT_NAME setup --non-interactive   # Automated setup"
    echo "  $SCRIPT_NAME start                     # Start automation"
    echo "  $SCRIPT_NAME status                    # Check status"
    echo "  $SCRIPT_NAME logs                      # View logs"
    echo ""
}

main() {
    # Separate command from options by processing all arguments
    local command="setup"  # default command
    local temp_args=()
    
    # First pass: extract command and collect all other arguments
    for arg in "$@"; do
        case "$arg" in
            setup|start|stop|restart|status|logs|validate)
                command="$arg"
                ;;
            *)
                temp_args+=("$arg")
                ;;
        esac
    done
    
    # Second pass: process options
    set -- "${temp_args[@]}"  # Replace $@ with filtered arguments
    while [[ $# -gt 0 ]]; do
        case "$1" in
            --non-interactive)
                export NON_INTERACTIVE="true"
                setup_debug "Non-interactive mode enabled"
                shift
                ;;
            --force-rebuild)
                export FORCE_REBUILD="true"
                setup_debug "Force rebuild enabled"
                shift
                ;;
            --debug)
                export CONFIG_DEBUG="true"
                setup_debug "Debug logging enabled"
                shift
                ;;
            -h|--help)
                show_help
                exit 0
                ;;
            -*)
                setup_error "Unknown option: $1"
                show_help
                exit 1
                ;;
            *)
                # Skip any remaining non-option arguments
                shift
                ;;
        esac
    done
    
    case "$command" in
        setup)
            run_interactive_setup
            ;;
        start)
            service_start
            ;;
        stop)
            service_stop
            ;;
        restart)
            service_restart
            ;;
        status)
            service_status
            ;;
        logs)
            service_logs
            ;;
        validate)
            validate_complete_setup
            ;;
        help)
            show_help
            ;;
        *)
            setup_error "Unknown command: $command"
            show_help
            exit 1
            ;;
    esac
}

# Run main function with all arguments
main "$@"