#!/bin/bash

# ThrillWiki Step 5A Service Configuration - Simple Compatibility Test
# Tests systemd service configuration and cross-shell compatibility
# This is a non-interactive version focused on service file validation

set -e

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

PROJECT_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"

# Color definitions
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# Logging functions
test_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

test_success() {
    echo -e "${GREEN}[SUCCESS]${NC} ✅ $1"
}

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

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

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

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

# Test cross-shell compatibility
test_shell_compatibility() {
    local current_shell
    current_shell=$(get_shell)
    
    test_info "Testing shell compatibility in $current_shell..."
    
    # Test directory detection
    if [ -d "$SCRIPT_DIR" ] && [ -d "$PROJECT_DIR" ]; then
        test_success "Directory detection works in $current_shell"
    else
        test_error "Directory detection failed in $current_shell"
        return 1
    fi
    
    # Test variable expansion
    local test_var="value"
    local expanded="${test_var:-default}"
    if [ "$expanded" = "value" ]; then
        test_success "Variable expansion works in $current_shell"
    else
        test_error "Variable expansion failed in $current_shell"
        return 1
    fi
    
    return 0
}

# Main test function
run_tests() {
    local current_shell
    current_shell=$(get_shell)
    
    echo
    echo "🧪 ThrillWiki Step 5A Service Configuration Test"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo "Testing in $current_shell shell"
    echo
    
    # Run tests
    if ! test_shell_compatibility; then
        return 1
    fi
    
    if ! test_service_files; then
        return 1
    fi
    
    if ! test_automation_script; then
        return 1
    fi
    
    echo
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    test_success "All Step 5A service configuration tests passed! 🎉"
    echo "✅ Service configuration is compatible with $current_shell shell"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo
    
    return 0
}

# Test in both shells
main() {
    echo "Testing Step 5A compatibility..."
    
    # Test in bash
    echo
    test_info "Testing in bash shell"
    if bash "$0" run_tests; then
        test_success "bash compatibility test passed"
    else
        test_error "bash compatibility test failed"
        return 1
    fi
    
    # Test in zsh (if available)
    if command -v zsh >/dev/null 2>&1; then
        echo
        test_info "Testing in zsh shell"
        if zsh "$0" run_tests; then
            test_success "zsh compatibility test passed"
        else
            test_error "zsh compatibility test failed"
            return 1
        fi
    else
        test_info "zsh not available, skipping zsh test"
    fi
    
    echo
    test_success "All cross-shell compatibility tests completed successfully! 🎉"
    return 0
}

# Check if we're being called to run tests directly
if [ "$1" = "run_tests" ]; then
    run_tests
else
    main
fi