# Module: Configuration Testing Utilities
# Purpose: Provides testing infrastructure for configuration loading, interpolation, and validation.
# Dependencies: interpolators, validators

# Configuration Loader - Testing and Interpolation Functions
# Provides testing utilities for configuration loading and interpolation

# Selective imports (ADR-025 Phase 3 Layer 2).
# config/interpolators star-import was dead — dropped.
use lib_provisioning/config/validators.nu [validate-interpolation]

# Test interpolation with sample data
export def test-interpolation [
    --sample: string = "basic"      # Sample test data: basic, advanced, all
] {
    print "🧪 Testing Enhanced Interpolation System"
    print ""

    # Define test configurations based on sample type
    let test_config = match $sample {
        "basic" => {
            paths: { base: "/usr/local/provisioning" }
            test_patterns: {
                simple_path: "{{paths.base}}/config"
                env_home: "{{env.HOME}}/configs"
                current_date: "backup-{{now.date}}"
            }
        }
        "advanced" => {
            paths: { base: "/usr/local/provisioning" }
            providers: { aws: { region: "us-west-2" }, default: "aws" }
            sops: { key_file: "{{env.HOME}}/.age/key.txt" }
            test_patterns: {
                complex_path: "{{path.join(paths.base, \"custom\")}}"
                provider_ref: "Region: {{providers.aws.region}}"
                git_info: "Build: {{git.branch}}-{{git.commit}}"
                conditional: "{{env.HOME || \"/tmp\"}}/cache"
            }
        }
        _ => {
            paths: { base: "/usr/local/provisioning" }
            providers: { aws: { region: "us-west-2" }, default: "aws" }
            sops: { key_file: "{{env.HOME}}/.age/key.txt", config_path: "/etc/sops.yaml" }
            current_environment: "test"
            test_patterns: {
                all_patterns: "{{paths.base}}/{{env.USER}}/{{now.date}}/{{git.branch}}/{{providers.default}}"
                function_call: "{{path.join(paths.base, \"providers\")}}"
                sops_refs: "Key: {{sops.key_file}}, Config: {{sops.config_path}}"
                datetime: "{{now.date}} at {{now.timestamp}}"
            }
        }
    }

    # Test interpolation
    print $"Testing with ($sample) sample configuration..."
    print ""

    let base_path = "/usr/local/provisioning"
    let interpolated_config = (interpolate-all-paths $test_config $base_path)

    # Show results
    print "📋 Original patterns:"
    for key in ($test_config.test_patterns | columns) {
        let original = ($test_config.test_patterns | get $key)
        print $"  ($key): ($original)"
    }

    print ""
    print "✨ Interpolated results:"
    for key in ($interpolated_config.test_patterns | columns) {
        let interpolated = ($interpolated_config.test_patterns | get $key)
        print $"  ($key): ($interpolated)"
    }

    print ""

    # Validate interpolation
    let validation = (validate-interpolation $test_config --detailed true)
    if $validation.valid {
        print "✅ Interpolation validation passed"
    } else {
        print "❌ Interpolation validation failed:"
        for error in $validation.errors {
            print $"  Error: ($error.message)"
        }
    }

    if ($validation.warnings | length) > 0 {
        print "⚠️  Warnings:"
        for warning in $validation.warnings {
            print $"  Warning: ($warning.message)"
        }
    }

    print ""
    print $"📊 Summary: ($validation.summary.interpolation_patterns_detected) interpolation patterns processed"

    $interpolated_config
}

# Create comprehensive interpolation test suite
export def create-interpolation-test-suite [
    --output-file: string = "interpolation_test_results.json"
] {
    print "🧪 Creating Comprehensive Interpolation Test Suite"
    print "=================================================="
    print ""

    mut test_results = []

    # Test 1: Basic patterns
    print "🔍 Test 1: Basic Interpolation Patterns"
    let basic_test = (run-interpolation-test "basic")
    $test_results = ($test_results | append {
        test_name: "basic_patterns"
        passed: $basic_test.passed
        details: $basic_test.details
        timestamp: (date now | format date "%Y-%m-%d %H:%M:%S")
    })

    # Test 2: Environment variables
    print "🔍 Test 2: Environment Variable Interpolation"
    let env_test = (run-interpolation-test "environment")
    $test_results = ($test_results | append {
        test_name: "environment_variables"
        passed: $env_test.passed
        details: $env_test.details
        timestamp: (date now | format date "%Y-%m-%d %H:%M:%S")
    })

    # Test 3: Security validation
    print "🔍 Test 3: Security Validation"
    let security_test = (run-security-test)
    $test_results = ($test_results | append {
        test_name: "security_validation"
        passed: $security_test.passed
        details: $security_test.details
        timestamp: (date now | format date "%Y-%m-%d %H:%M:%S")
    })

    # Test 4: Advanced patterns
    print "🔍 Test 4: Advanced Interpolation Features"
    let advanced_test = (run-interpolation-test "advanced")
    $test_results = ($test_results | append {
        test_name: "advanced_patterns"
        passed: $advanced_test.passed
        details: $advanced_test.details
        timestamp: (date now | format date "%Y-%m-%d %H:%M:%S")
    })

    # Save results
    $test_results | to json | save --force $output_file

    # Summary
    let total_tests = ($test_results | length)
    let passed_tests = ($test_results | where passed == true | length)
    let failed_tests = ($total_tests - $passed_tests)

    print ""
    print "📊 Test Suite Summary"
    print "===================="
    print $"   Total tests: ($total_tests)"
    print $"   Passed: ($passed_tests)"
    print $"   Failed: ($failed_tests)"
    print ""

    if $failed_tests == 0 {
        print "✅ All interpolation tests passed!"
    } else {
        print "❌ Some interpolation tests failed!"
        print ""
        print "Failed tests:"
        for test in ($test_results | where passed == false) {
            print $"   • ($test.test_name): ($test.details.error)"
        }
    }

    print ""
    print $"📄 Detailed results saved to: ($output_file)"

    {
        total: $total_tests
        passed: $passed_tests
        failed: $failed_tests
        success_rate: (($passed_tests * 100) / $total_tests)
        results: $test_results
    }
}

# Run individual interpolation test
def run-interpolation-test [
    test_type: string
] {
    let test_result = (do {
        match $test_type {
            "basic" => {
                let test_config = {
                    paths: { base: "/test/path" }
                    test_value: "{{paths.base}}/config"
                }
                let result = (interpolate-all-paths $test_config "/test/path")
                let expected = "/test/path/config"
                let actual = ($result.test_value)

                if $actual == $expected {
                    { passed: true, details: { expected: $expected, actual: $actual } }
                } else {
                    { passed: false, details: { expected: $expected, actual: $actual, error: "Value mismatch" } }
                }
            }
            "environment" => {
                let test_config = {
                    paths: { base: "/test/path" }
                    test_value: "{{env.USER}}/config"
                }
                let result = (interpolate-all-paths $test_config "/test/path")
                let expected_pattern = ".*/config"  # USER should be replaced with something

                if ($result.test_value | str contains "/config") and not ($result.test_value | str contains "{{env.USER}}") {
                    { passed: true, details: { pattern: $expected_pattern, actual: $result.test_value } }
                } else {
                    { passed: false, details: { pattern: $expected_pattern, actual: $result.test_value, error: "Environment variable not interpolated" } }
                }
            }
            "advanced" => {
                let test_config = {
                    paths: { base: "/test/path" }
                    current_environment: "test"
                    test_values: {
                        date_test: "backup-{{now.date}}"
                        git_test: "build-{{git.branch}}"
                    }
                }
                let result = (interpolate-all-paths $test_config "/test/path")

                # Check if date was interpolated (should not contain {{now.date}})
                let date_ok = not ($result.test_values.date_test | str contains "{{now.date}}")
                # Check if git was interpolated (should not contain {{git.branch}})
                let git_ok = not ($result.test_values.git_test | str contains "{{git.branch}}")

                if $date_ok and $git_ok {
                    { passed: true, details: { date_result: $result.test_values.date_test, git_result: $result.test_values.git_test } }
                } else {
                    { passed: false, details: { date_result: $result.test_values.date_test, git_result: $result.test_values.git_test, error: "Advanced patterns not interpolated" } }
                }
            }
            _ => {
                { passed: false, details: { error: $"Unknown test type: ($test_type)" } }
            }
        }
    } | complete)

    if $test_result.exit_code != 0 {
        { passed: false, details: { error: $"Test execution failed: ($test_result.stderr)" } }
    } else {
        $test_result.stdout
    }
}

# Run security validation test
def run-security-test [] {
    let security_result = (do {
        # Test 1: Safe configuration should pass
        let safe_config = {
            paths: { base: "/safe/path" }
            test_value: "{{env.HOME}}/config"
        }

        let safe_result = (validate-interpolation-security $safe_config false)

        # Test 2: Unsafe configuration should fail
        let unsafe_config = {
            paths: { base: "/unsafe/path" }
            test_value: "{{env.PATH}}/config"  # PATH is considered unsafe
        }

        let unsafe_result = (validate-interpolation-security $unsafe_config false)

        if $safe_result.valid and (not $unsafe_result.valid) {
            { passed: true, details: { safe_passed: $safe_result.valid, unsafe_blocked: (not $unsafe_result.valid) } }
        } else {
            { passed: false, details: { safe_passed: $safe_result.valid, unsafe_blocked: (not $unsafe_result.valid), error: "Security validation not working correctly" } }
        }
    } | complete)

    if $security_result.exit_code != 0 {
        { passed: false, details: { error: $"Security test execution failed: ($security_result.stderr)" } }
    } else {
        $security_result.stdout
    }
}
