#!/usr/bin/env bash
#
# ThrillWiki Step 5A Cross-Shell Compatibility Test
# Tests service configuration and startup functionality in both bash and zsh
#
# Features tested:
# - Service configuration functions
# - Environment file generation
# - Systemd service integration
# - Timer configuration
# - Health monitoring
# - Cross-shell compatibility
#

set -e

# [AWS-SECRET-REMOVED]====================================
# SCRIPT CONFIGURATION
# [AWS-SECRET-REMOVED]====================================

# Cross-shell compatible script directory detection
if [ -n "${BASH_SOURCE:-}" ]; then
    SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
    SCRIPT_NAME="$(basename "${BASH_SOURCE[0]}")"
elif [ -n "${ZSH_NAME:-}" ]; then
    SCRIPT_DIR="$(cd "$(dirname "${(%):-%x}")" && pwd)"
    SCRIPT_NAME="$(basename "${(%):-%x}")"
else
    SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
    SCRIPT_NAME="$(basename "$0")"
fi

PROJECT_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"
DEPLOY_COMPLETE_SCRIPT="$SCRIPT_DIR/deploy-complete.sh"

# Test configuration
TEST_LOG="$PROJECT_DIR/logs/test-step5a-compatibility.log"
TEST_HOST="localhost"
TEST_PRESET="dev"
TEST_TOKEN="test_token_value"

# [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]====================================

test_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 "$TEST_LOG")"
    
    # Log to file (without colors)
    echo "[$timestamp] [$level] [STEP5A-TEST] $message" >> "$TEST_LOG"
    
    # Log to console (with colors)
    echo -e "${color}[$timestamp] [STEP5A-TEST-$level]${NC} $message"
}

test_info() {
    test_log "INFO" "$BLUE" "$1"
}

test_success() {
    test_log "SUCCESS" "$GREEN" "✅ $1"
}

test_warning() {
    test_log "WARNING" "$YELLOW" "⚠️  $1"
}

test_error() {
    test_log "ERROR" "$RED" "❌ $1"
}

test_debug() {
    if [ "${TEST_DEBUG:-false}" = "true" ]; then
        test_log "DEBUG" "$PURPLE" "🔍 $1"
    fi
}

test_progress() {
    test_log "PROGRESS" "$CYAN" "🚀 $1"
}

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

# Cross-shell compatible command existence check
command_exists() {
    command -v "$1" >/dev/null 2>&1
}

# Get current shell name
get_current_shell() {
    if [ -n "${BASH_VERSION:-}" ]; then
        echo "bash"
    elif [ -n "${ZSH_VERSION:-}" ]; then
        echo "zsh"
    else
        echo "unknown"
    fi
}

# Test shell detection
test_shell_detection() {
    local current_shell
    current_shell=$(get_current_shell)
    
    test_info "Testing shell detection in $current_shell"
    
    # Test script directory detection
    if [ -d "$SCRIPT_DIR" ] && [ -f "$SCRIPT_DIR/$SCRIPT_NAME" ]; then
        test_success "Script directory detection works in $current_shell"
    else
        test_error "Script directory detection failed in $current_shell"
        return 1
    fi
    
    # Test project directory detection
    if [ -d "$PROJECT_DIR" ] && [ -f "$PROJECT_DIR/manage.py" ]; then
        test_success "Project directory detection works in $current_shell"
    else
        test_error "Project directory detection failed in $current_shell"
        return 1
    fi
    
    return 0
}

# [AWS-SECRET-REMOVED]====================================
# SERVICE CONFIGURATION TESTING
# [AWS-SECRET-REMOVED]====================================

# Test deployment preset configuration functions
test_preset_configuration() {
    test_info "Testing deployment preset configuration functions"
    
    # Source the deploy-complete script to access functions
    source "$DEPLOY_COMPLETE_SCRIPT"
    
    # Test preset validation
    if validate_preset "dev"; then
        test_success "Preset validation works for 'dev'"
    else
        test_error "Preset validation failed for 'dev'"
        return 1
    fi
    
    if validate_preset "invalid_preset"; then
        test_error "Preset validation incorrectly accepted invalid preset"
        return 1
    else
        test_success "Preset validation correctly rejected invalid preset"
    fi
    
    # Test preset configuration retrieval
    local pull_interval
    pull_interval=$(get_preset_config "dev" "PULL_INTERVAL")
    if [ "$pull_interval" = "60" ]; then
        test_success "Preset config retrieval works for dev PULL_INTERVAL: $pull_interval"
    else
        test_error "Preset config retrieval failed for dev PULL_INTERVAL: got '$pull_interval', expected '60'"
        return 1
    fi
    
    # Test all presets
    local presets="dev prod demo testing"
    for preset in $presets; do
        local description
        description=$(get_deployment_preset_description "$preset")
        if [ -n "$description" ] && [ "$description" != "Unknown preset" ]; then
            test_success "Preset description works for '$preset': $description"
        else
            test_error "Preset description failed for '$preset'"
            return 1
        fi
    done
    
    return 0
}

# Test environment file generation
test_environment_generation() {
    test_info "Testing environment file generation"
    
    # Source the deploy-complete script to access functions
    source "$DEPLOY_COMPLETE_SCRIPT"
    
    # Create temporary test directory
    local test_dir="/tmp/thrillwiki-test-$$"
    mkdir -p "$test_dir/scripts/systemd"
    
    # Mock SSH command function for testing
    generate_test_env_config() {
        local preset="$1"
        local github_token="$2"
        
        # Simulate the environment generation logic
        local pull_interval
        pull_interval=$(get_preset_config "$preset" "PULL_INTERVAL")
        
        local health_check_interval
        health_check_interval=$(get_preset_config "$preset" "HEALTH_CHECK_INTERVAL")
        
        local debug_mode
        debug_mode=$(get_preset_config "$preset" "DEBUG_MODE")
        
        # Generate test environment file
        cat > "$test_dir/scripts/systemd/thrillwiki-deployment***REMOVED***" << EOF
# Test Environment Configuration
PROJECT_DIR=$test_dir
DEPLOYMENT_PRESET=$preset
PULL_INTERVAL=$pull_interval
HEALTH_CHECK_INTERVAL=$health_check_interval
DEBUG_MODE=$debug_mode
GITHUB_TOKEN=$github_token
EOF
        
        return 0
    }
    
    # Test environment generation for different presets
    local presets="dev prod demo testing"
    for preset in $presets; do
        if generate_test_env_config "$preset" "$TEST_TOKEN"; then
            local env_file="$test_dir/scripts/systemd/thrillwiki-deployment***REMOVED***"
            if [ -f "$env_file" ]; then
                # Verify content
                if grep -q "DEPLOYMENT_PRESET=$preset" "$env_file" && \
                   grep -q "GITHUB_TOKEN=$TEST_TOKEN" "$env_file"; then
                    test_success "Environment generation works for preset '$preset'"
                else
                    test_error "Environment generation produced incorrect content for preset '$preset'"
                    cat "$env_file"
                    rm -rf "$test_dir"
                    return 1
                fi
            else
                test_error "Environment file not created for preset '$preset'"
                rm -rf "$test_dir"
                return 1
            fi
        else
            test_error "Environment generation failed for preset '$preset'"
            rm -rf "$test_dir"
            return 1
        fi
    done
    
    # Cleanup
    rm -rf "$test_dir"
    
    return 0
}

# Test systemd service file validation
test_systemd_service_files() {
    test_info "Testing systemd service file validation"
    
    local systemd_dir="$PROJECT_DIR/scripts/systemd"
    local required_files=(
        "thrillwiki-deployment.service"
        "thrillwiki-smart-deploy.service"
        "thrillwiki-smart-deploy.timer"
        "thrillwiki-deployment***REMOVED***"
    )
    
    # Check if service files exist
    for file in "${required_files[@]}"; do
        local file_path="$systemd_dir/$file"
        if [ -f "$file_path" ]; then
            test_success "Service file exists: $file"
            
            # Basic syntax validation for service files
            if [[ "$file" == *.service ]] || [[ "$file" == *.timer ]]; then
                if grep -q "^\[Unit\]" "$file_path" && \
                   grep -q "^\[Install\]" "$file_path"; then
                    test_success "Service file has valid structure: $file"
                else
                    test_error "Service file has invalid structure: $file"
                    return 1
                fi
            fi
        else
            test_error "Required service file missing: $file"
            return 1
        fi
    done
    
    return 0
}

# Test deployment automation script
test_deployment_automation_script() {
    test_info "Testing deployment automation script"
    
    local automation_script="$PROJECT_DIR/scripts/vm/deploy-automation.sh"
    
    if [ -f "$automation_script" ]; then
        test_success "Deployment automation script exists"
        
        if [ -x "$automation_script" ]; then
            test_success "Deployment automation script is executable"
        else
            test_error "Deployment automation script is not executable"
            return 1
        fi
        
        # Test script syntax
        if bash -n "$automation_script"; then
            test_success "Deployment automation script has valid bash syntax"
        else
            test_error "Deployment automation script has syntax errors"
            return 1
        fi
        
        # Test script commands
        local commands="start stop status health-check restart-smart-deploy restart-server"
        for cmd in $commands; do
            if grep -q "$cmd)" "$automation_script"; then
                test_success "Deployment automation script supports command: $cmd"
            else
                test_error "Deployment automation script missing command: $cmd"
                return 1
            fi
        done
    else
        test_error "Deployment automation script not found"
        return 1
    fi
    
    return 0
}

# [AWS-SECRET-REMOVED]====================================
# CROSS-SHELL COMPATIBILITY TESTING
# [AWS-SECRET-REMOVED]====================================

# Test function availability in both shells
test_function_availability() {
    test_info "Testing function availability"
    
    # Source the deploy-complete script
    source "$DEPLOY_COMPLETE_SCRIPT"
    
    # Test critical functions
    local functions=(
        "get_preset_config"
        "get_deployment_preset_description"
        "validate_preset"
        "configure_deployment_services"
        "generate_deployment_environment_config"
        "configure_deployment_timer"
        "install_systemd_services"
        "enable_and_start_services"
        "monitor_service_health"
    )
    
    for func in "${functions[@]}"; do
        if command_exists "$func" || type "$func" >/dev/null 2>&1; then
            test_success "Function available: $func"
        else
            test_error "Function not available: $func"
            return 1
        fi
    done
    
    return 0
}

# Test variable expansion and substitution
test_variable_expansion() {
    test_info "Testing variable expansion and substitution"
    
    # Test basic variable expansion
    local test_var="test_value"
    local expanded="${test_var:-default}"
    
    if [ "$expanded" = "test_value" ]; then
        test_success "Basic variable expansion works"
    else
        test_error "Basic variable expansion failed: got '$expanded', expected 'test_value'"
        return 1
    fi
    
    # Test default value expansion
    local empty_var=""
    local default_expanded="${empty_var:-default_value}"
    
    if [ "$default_expanded" = "default_value" ]; then
        test_success "Default value expansion works"
    else
        test_error "Default value expansion failed: got '$default_expanded', expected 'default_value'"
        return 1
    fi
    
    # Test array compatibility (where supported)
    local array_test=(item1 item2 item3)
    if [ "${#array_test[@]}" -eq 3 ]; then
        test_success "Array operations work"
    else
        test_warning "Array operations may not be fully compatible"
    fi
    
    return 0
}

# [AWS-SECRET-REMOVED]====================================
# MAIN TEST EXECUTION
# [AWS-SECRET-REMOVED]====================================

# Run all tests
run_all_tests() {
    local current_shell
    current_shell=$(get_current_shell)
    
    test_info "Starting Step 5A compatibility tests in $current_shell shell"
    test_info "Test log: $TEST_LOG"
    
    local test_failures=0
    
    # Test 1: Shell detection
    test_progress "Test 1: Shell detection"
    if ! test_shell_detection; then
        ((test_failures++))
    fi
    
    # Test 2: Preset configuration
    test_progress "Test 2: Preset configuration"
    if ! test_preset_configuration; then
        ((test_failures++))
    fi
    
    # Test 3: Environment generation
    test_progress "Test 3: Environment generation"
    if ! test_environment_generation; then
        ((test_failures++))
    fi
    
    # Test 4: Systemd service files
    test_progress "Test 4: Systemd service files"
    if ! test_systemd_service_files; then
        ((test_failures++))
    fi
    
    # Test 5: Deployment automation script
    test_progress "Test 5: Deployment automation script"
    if ! test_deployment_automation_script; then
        ((test_failures++))
    fi
    
    # Test 6: Function availability
    test_progress "Test 6: Function availability"
    if ! test_function_availability; then
        ((test_failures++))
    fi
    
    # Test 7: Variable expansion
    test_progress "Test 7: Variable expansion"
    if ! test_variable_expansion; then
        ((test_failures++))
    fi
    
    # Report results
    echo ""
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    if [ $test_failures -eq 0 ]; then
        test_success "All Step 5A compatibility tests passed in $current_shell! 🎉"
        echo -e "${GREEN}✅ Step 5A service configuration is fully compatible with $current_shell shell${NC}"
    else
        test_error "Step 5A compatibility tests failed: $test_failures test(s) failed in $current_shell"
        echo -e "${RED}❌ Step 5A has compatibility issues with $current_shell shell${NC}"
    fi
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo ""
    
    return $test_failures
}

# Test in both shells if available
test_cross_shell_compatibility() {
    test_info "Testing cross-shell compatibility"
    
    local shells_to_test=()
    
    # Check available shells
    if command_exists bash; then
        shells_to_test+=("bash")
    fi
    
    if command_exists zsh; then
        shells_to_test+=("zsh")
    fi
    
    if [ ${#shells_to_test[@]} -eq 0 ]; then
        test_error "No compatible shells found for testing"
        return 1
    fi
    
    local total_failures=0
    
    for shell in "${shells_to_test[@]}"; do
        test_info "Testing in $shell shell"
        echo ""
        
        if "$shell" "$0" --single-shell; then
            test_success "$shell compatibility test passed"
        else
            test_error "$shell compatibility test failed"
            ((total_failures++))
        fi
        
        echo ""
    done
    
    if [ $total_failures -eq 0 ]; then
        test_success "Cross-shell compatibility verified for all available shells"
        return 0
    else
        test_error "Cross-shell compatibility issues detected ($total_failures shell(s) failed)"
        return 1
    fi
}

# [AWS-SECRET-REMOVED]====================================
# COMMAND HANDLING
# [AWS-SECRET-REMOVED]====================================

# Show usage information
show_usage() {
    cat << 'EOF'
🧪 ThrillWiki Step 5A Cross-Shell Compatibility Test

DESCRIPTION:
    Tests Step 5A service configuration and startup functionality for cross-shell
    compatibility between bash and zsh environments.

USAGE:
    ./test-step5a-compatibility.sh [OPTIONS]

OPTIONS:
    --single-shell    Run tests in current shell only (used internally)
    --debug          Enable debug logging
    -h, --help       Show this help message

FEATURES TESTED:
    ✅ Service configuration functions
    ✅ Environment file generation
    ✅ Systemd service integration
    ✅ Timer configuration
    ✅ Health monitoring
    ✅ Cross-shell compatibility
    ✅ Function availability
    ✅ Variable expansion

EXAMPLES:
    # Run compatibility tests
    ./test-step5a-compatibility.sh
    
    # Run with debug output
    ./test-step5a-compatibility.sh --debug

EXIT CODES:
    0   All tests passed
    1   Some tests failed

EOF
}

# Main execution
main() {
    local single_shell=false
    
    # Parse arguments
    while [[ $# -gt 0 ]]; do
        case $1 in
            --single-shell)
                single_shell=true
                shift
                ;;
            --debug)
                export TEST_DEBUG=true
                shift
                ;;
            -h|--help)
                show_usage
                exit 0
                ;;
            *)
                test_error "Unknown option: $1"
                show_usage
                exit 1
                ;;
        esac
    done
    
    # Run tests
    if [ "$single_shell" = "true" ]; then
        # Single shell test (called by cross-shell test)
        run_all_tests
    else
        # Full cross-shell compatibility test
        echo ""
        echo -e "${BOLD}${CYAN}🧪 ThrillWiki Step 5A Cross-Shell Compatibility Test${NC}"
        echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
        echo ""
        
        test_cross_shell_compatibility
    fi
}

# Cross-shell compatible script execution check
if [ -n "${BASH_SOURCE:-}" ]; then
    # In bash, check if script is executed directly
    if [ "${BASH_SOURCE[0]}" = "${0}" ]; then
        main "$@"
    fi
elif [ -n "${ZSH_NAME:-}" ]; then
    # In zsh, check if script is executed directly
    if [ "${(%):-%x}" = "${0}" ]; then
        main "$@"
    fi
else
    # In other shells, assume direct execution
    main "$@"
fi