#!/bin/bash

# Framework Functions Unit Tests
# Tests core framework functionality

set -euo pipefail

PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"

# Source framework functions from the vendored KNELShellFramework
FRAMEWORK_INCLUDES="$PROJECT_ROOT/vendor/git@git.knownelement.com/29418/KNEL/KNELShellFramework/Framework-Includes"
source "$FRAMEWORK_INCLUDES/Logging.sh" 2>/dev/null || echo "Warning: Logging.sh not found"
source "$FRAMEWORK_INCLUDES/PrettyPrint.sh" 2>/dev/null || echo "Warning: PrettyPrint.sh not found"
source "$FRAMEWORK_INCLUDES/ErrorHandling.sh" 2>/dev/null || echo "Warning: ErrorHandling.sh not found"

function test_logging_variables() {
    echo "🔍 Testing logging variables..."

    if [[ -n "${CURRENT_TIMESTAMP:-}" ]]; then
        echo "✅ CURRENT_TIMESTAMP is set"
    else
        echo "❌ CURRENT_TIMESTAMP is not set"
        return 1
    fi

    if [[ -n "${LOGFILENAME:-}" ]]; then
        echo "✅ LOGFILENAME is set"
    else
        echo "❌ LOGFILENAME is not set"
        return 1
    fi

    return 0
}

function test_pretty_print_functions() {
    echo "🔍 Testing pretty print functions..."
    
    # Test if pretty print functions exist
    if command -v print_info >/dev/null 2>&1; then
        print_info "Test info message" >/dev/null 2>&1 || true
        echo "✅ print_info function exists"
    else
        echo "❌ print_info function missing"
        return 1
    fi
    
    if command -v print_error >/dev/null 2>&1; then
        print_error "Test error message" >/dev/null 2>&1 || true
        echo "✅ print_error function exists"
    else
        echo "❌ print_error function missing"
        return 1
    fi
    
    return 0
}

function test_error_handling() {
    echo "🔍 Testing error handling..."
    
    # Test if error handling functions exist
    if command -v error_out >/dev/null 2>&1; then
        echo "✅ error_out function exists"
    else
        echo "❌ error_out function missing"
        return 1
    fi

    if command -v handle_failure >/dev/null 2>&1; then
        echo "✅ handle_failure function exists"
    else
        echo "❌ handle_failure function missing"
        return 1
    fi
    
    # Test bash strict mode is set
    if [[ "$-" == *e* ]]; then
        echo "✅ Bash strict mode (set -e) is enabled"
    else
        echo "❌ Bash strict mode (set -e) not enabled"
        return 1
    fi
    
    if [[ "$-" == *u* ]]; then
        echo "✅ Bash unset variable checking (set -u) is enabled"
    else
        echo "❌ Bash unset variable checking (set -u) not enabled"
        return 1
    fi
    
    return 0
}

function test_framework_includes_exist() {
    echo "🔍 Testing framework includes exist..."
    
    local required_includes=(
        "Logging.sh"
        "PrettyPrint.sh"
        "ErrorHandling.sh"
        "PreflightCheck.sh"
    )
    
    local missing_files=0
    
    for include_file in "${required_includes[@]}"; do
        if [[ -f "$FRAMEWORK_INCLUDES/$include_file" ]]; then
            echo "✅ Framework include exists: $include_file"
        else
            echo "❌ Framework include missing: $include_file"
            ((++missing_files))
        fi
    done
    
    return $missing_files
}

function test_syntax_validation() {
    echo "🔍 Testing script syntax validation..."
    
    local syntax_errors=0
    local script_dirs=(
        "$FRAMEWORK_INCLUDES"
        "$PROJECT_ROOT/Project-Includes"
        "$PROJECT_ROOT/ProjectCode"
    )

    for dir in "${script_dirs[@]}"; do
        if [[ -d "$dir" ]]; then
            while IFS= read -r -d '' file; do
                # Skip files that aren't bash scripts despite a .sh extension (e.g. PHP agents)
                local shebang
                shebang="$(head -c 32 "$file" 2>/dev/null)"
                case "$shebang" in
                    *php*|*python*|*perl*) continue ;;
                esac
                if bash -n "$file" 2>/dev/null; then
                    echo "✅ Syntax valid: $(basename "$file")"
                else
                    echo "❌ Syntax error in: $(basename "$file")"
                    ((++syntax_errors))
                fi
            done < <(find "$dir" -name "*.sh" -type f -print0)
        fi
    done
    
    return $syntax_errors
}

# Main test execution
function main() {
    echo "🧪 Running Framework Functions Unit Tests"
    echo "========================================"
    
    local total_failures=0
    
    # Run all unit tests
    test_framework_includes_exist || ((total_failures++))
    test_logging_variables || ((total_failures++))
    test_pretty_print_functions || ((total_failures++))
    test_error_handling || ((total_failures++))
    test_syntax_validation || ((total_failures++))
    
    echo "========================================"
    
    if [[ $total_failures -eq 0 ]]; then
        echo "✅ All framework function unit tests passed"
        exit 0
    else
        echo "❌ $total_failures framework function unit tests failed"
        exit 1
    fi
}

# Run main if executed directly
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    main "$@"
fi