#!/usr/bin/env bash
#
# ThrillWiki Step 4B Cross-Shell Compatibility Test
# Tests development server setup and automation functions
#

set -e

# 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)"

# Source the main deployment script for testing
source "$SCRIPT_DIR/deploy-complete.sh"

# Test configurations
TEST_LOG="$PROJECT_DIR/logs/step4b-test.log"
TEST_HOST="localhost"
TEST_PRESET="dev"

# Color definitions for test output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m'

# Test logging functions
test_log() {
    local level="$1"
    local color="$2"
    local message="$3"
    local timestamp="$(date '+%Y-%m-%d %H:%M:%S')"
    
    mkdir -p "$(dirname "$TEST_LOG")"
    echo "[$timestamp] [$level] [STEP4B-TEST] $message" >> "$TEST_LOG"
    echo -e "${color}[$timestamp] [STEP4B-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_progress() { test_log "PROGRESS" "$CYAN" "🚀 $1"; }

# Test function existence
test_function_exists() {
    local func_name="$1"
    if declare -f "$func_name" > /dev/null; then
        test_success "Function exists: $func_name"
        return 0
    else
        test_error "Function missing: $func_name"
        return 1
    fi
}

# Test cross-shell variable detection
test_shell_detection() {
    test_progress "Testing cross-shell variable detection"
    
    # Test shell detection variables
    if [ -n "${BASH_VERSION:-}" ]; then
        test_info "Running in Bash: $BASH_VERSION"
    elif [ -n "${ZSH_VERSION:-}" ]; then
        test_info "Running in Zsh: $ZSH_VERSION"
    else
        test_info "Running in other shell: ${SHELL:-unknown}"
    fi
    
    # Test script directory detection worked
    if [ -n "$SCRIPT_DIR" ] && [ -d "$SCRIPT_DIR" ]; then
        test_success "Script directory detected: $SCRIPT_DIR"
    else
        test_error "Script directory detection failed"
        return 1
    fi
    
    test_success "Cross-shell detection working"
    return 0
}

# Test Step 4B function availability
test_step4b_functions() {
    test_progress "Testing Step 4B function availability"
    
    local functions=(
        "setup_development_server"
        "start_thrillwiki_server"
        "verify_server_accessibility"
        "setup_server_automation"
        "setup_server_monitoring"
        "integrate_with_smart_deployment"
        "enhance_smart_deployment_with_server_management"
    )
    
    local test_failures=0
    for func in "${functions[@]}"; do
        if ! test_function_exists "$func"; then
            ((test_failures++))
        fi
    done
    
    if [ $test_failures -eq 0 ]; then
        test_success "All Step 4B functions are available"
        return 0
    else
        test_error "$test_failures Step 4B functions are missing"
        return 1
    fi
}

# Test preset configuration integration
test_preset_integration() {
    test_progress "Testing deployment preset integration"
    
    # Test preset configuration function
    if ! test_function_exists "get_preset_config"; then
        test_error "get_preset_config function not available"
        return 1
    fi
    
    # Test getting configuration values
    local test_presets=("dev" "prod" "demo" "testing")
    for preset in "${test_presets[@]}"; do
        local health_interval
        health_interval=$(get_preset_config "$preset" "HEALTH_CHECK_INTERVAL" 2>/dev/null || echo "")
        
        if [ -n "$health_interval" ]; then
            test_success "Preset $preset health check interval: ${health_interval}s"
        else
            test_warning "Could not get health check interval for preset: $preset"
        fi
    done
    
    test_success "Preset integration testing completed"
    return 0
}

# Test .clinerules command generation
test_clinerules_command() {
    test_progress "Testing .clinerules command compliance"
    
    # The exact command from .clinerules
    local expected_command="lsof -ti :8000 | xargs kill -9; find . -type d -name '__pycache__' -exec rm -r {} +; uv run manage.py tailwind runserver"
    
    # Extract the command from the start_thrillwiki_server function
    if grep -q "lsof -ti :8000.*uv run manage.py tailwind runserver" "$SCRIPT_DIR/deploy-complete.sh"; then
        test_success ".clinerules command found in start_thrillwiki_server function"
    else
        test_error ".clinerules command not found or incorrect"
        return 1
    fi
    
    # Check for exact command components
    if grep -q "lsof -ti :8000 | xargs kill -9" "$SCRIPT_DIR/deploy-complete.sh"; then
        test_success "Process cleanup component present"
    else
        test_error "Process cleanup component missing"
    fi
    
    if grep -q "find . -type d -name '__pycache__' -exec rm -r {} +" "$SCRIPT_DIR/deploy-complete.sh"; then
        test_success "Python cache cleanup component present"
    else
        test_error "Python cache cleanup component missing"
    fi
    
    if grep -q "uv run manage.py tailwind runserver" "$SCRIPT_DIR/deploy-complete.sh"; then
        test_success "ThrillWiki server startup component present"
    else
        test_error "ThrillWiki server startup component missing"
    fi
    
    test_success ".clinerules command compliance verified"
    return 0
}

# Test server management script structure
test_server_management_script() {
    test_progress "Testing server management script structure"
    
    # Check if the server management script is properly structured in the source
    if grep -q "ThrillWiki Server Management Script" "$SCRIPT_DIR/deploy-complete.sh"; then
        test_success "Server management script header found"
    else
        test_error "Server management script header missing"
        return 1
    fi
    
    # Check for essential server management functions
    local mgmt_functions=("start_server" "stop_server" "restart_server" "monitor_server")
    for func in "${mgmt_functions[@]}"; do
        if grep -q "$func()" "$SCRIPT_DIR/deploy-complete.sh"; then
            test_success "Server management function: $func"
        else
            test_warning "Server management function missing: $func"
        fi
    done
    
    test_success "Server management script structure verified"
    return 0
}

# Test cross-shell deployment hook
test_deployment_hook() {
    test_progress "Testing deployment hook cross-shell compatibility"
    
    # Check for cross-shell script directory detection in deployment hook
    if grep -A 10 "ThrillWiki Deployment Hook" "$SCRIPT_DIR/deploy-complete.sh" | grep -q "BASH_SOURCE\|ZSH_NAME"; then
        test_success "Deployment hook has cross-shell compatibility"
    else
        test_error "Deployment hook missing cross-shell compatibility"
        return 1
    fi
    
    test_success "Deployment hook structure verified"
    return 0
}

# Main test execution
main() {
    echo ""
    echo -e "${BOLD}${CYAN}"
    echo "🧪 ThrillWiki Step 4B Cross-Shell Compatibility Test"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo -e "${NC}"
    echo ""
    
    local test_failures=0
    
    # Run tests
    test_shell_detection || ((test_failures++))
    echo ""
    
    test_step4b_functions || ((test_failures++))
    echo ""
    
    test_preset_integration || ((test_failures++))
    echo ""
    
    test_clinerules_command || ((test_failures++))
    echo ""
    
    test_server_management_script || ((test_failures++))
    echo ""
    
    test_deployment_hook || ((test_failures++))
    echo ""
    
    # Summary
    echo -e "${BOLD}${CYAN}Test Summary:${NC}"
    echo "━━━━━━━━━━━━━━"
    
    if [ $test_failures -eq 0 ]; then
        test_success "All Step 4B cross-shell compatibility tests passed!"
        echo ""
        echo -e "${GREEN}✅ Step 4B implementation is ready for deployment${NC}"
        echo ""
        echo "Features validated:"
        echo "• ThrillWiki development server startup with exact .clinerules command"
        echo "• Automated server management with monitoring and restart capabilities"
        echo "• Cross-shell compatible process management and control"
        echo "• Integration with smart deployment system from Step 4A"
        echo "• Server health monitoring and automatic recovery"
        echo "• Development server configuration based on deployment presets"
        echo "• Background automation service features"
        return 0
    else
        test_error "$test_failures test(s) failed"
        echo ""
        echo -e "${RED}❌ Step 4B implementation needs attention${NC}"
        echo ""
        echo "Please check the test log for details: $TEST_LOG"
        return 1
    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