# Test Script for Provider-Agnostic Architecture
# Validates the new provider system works correctly

use ../core/nulib/lib_provisioning/providers/registry.nu *
use ../core/nulib/lib_provisioning/providers/loader.nu *
use ../core/nulib/lib_provisioning/providers/interface.nu *
use ../core/nulib/lib_provisioning/utils/logging.nu *
use ../extensions/providers/prov_lib/middleware_provider_agnostic.nu *

# Test provider registry
export def test-provider-registry []: nothing -> nothing {
    log-section "Testing Provider Registry" "test"

    # Initialize registry
    init-provider-registry

    # List providers
    log-info "Listing available providers..." "test"
    let providers = (list-providers)
    print ($providers | table)

    # Get provider stats
    let stats = (get-provider-stats)
    log-info $"Registry stats: ($stats.total_providers) total, ($stats.available_providers) available" "test"

    # Test provider availability
    for provider_name in ["aws", "upcloud", "local"] {
        let available = (is-provider-available $provider_name)
        if $available {
            log-success $"Provider ($provider_name) is available" "test"
        } else {
            log-warning $"Provider ($provider_name) is not available" "test"
        }
    }
}

# Test provider loading
export def test-provider-loading []: nothing -> nothing {
    log-section "Testing Provider Loading" "test"

    # Test loading individual providers
    for provider_name in ["aws", "upcloud", "local"] {
        log-info $"Testing load of provider: ($provider_name)" "test"

        let load_result = (do {
            load-provider $provider_name
        } | complete)

        let provider = if $load_result.exit_code == 0 {
            $load_result.stdout
        } else {
            log-error $"Failed to load ($provider_name): ($load_result.stderr)" "test"
            {}
        }

        if not ($provider | is-empty) {
            log-success $"Successfully loaded provider: ($provider_name)" "test"
        } else {
            log-error $"Failed to load provider: ($provider_name)" "test"
        }
    }

    # Test batch loading
    log-info "Testing batch provider loading..." "test"
    let batch_result = (load-providers ["aws", "upcloud", "local"])
    log-info $"Batch load result: ($batch_result.successful)/($batch_result.total) successful" "test"
}

# Test provider interface validation
export def test-provider-interface []: nothing -> nothing {
    log-section "Testing Provider Interface Validation" "test"

    # Get interface documentation
    let interface_docs = (get-provider-interface-docs)
    log-info $"Provider interface defines ($interface_docs | length) functions" "test"

    # Show some key functions
    let key_functions = ($interface_docs | where function in ["query_servers", "create_server", "get_ip"])
    print "Key provider functions:"
    print ($key_functions | table)
}

# Test middleware with mock settings
export def test-middleware []: nothing -> nothing {
    log-section "Testing Provider-Agnostic Middleware" "test"

    # Create mock settings for testing
    let mock_settings = {
        data: {
            servers: [
                {
                    hostname: "test-aws-server"
                    provider: "aws"
                    zone: "us-east-1"
                }
                {
                    hostname: "test-upcloud-server"
                    provider: "upcloud"
                    zone: "us-nyc1"
                }
                {
                    hostname: "test-local-server"
                    provider: "local"
                    zone: "datacenter1"
                }
            ]
        }
    }

    # Test provider status
    log-info "Getting provider status..." "test"
    let status = (mw_provider_status)
    print ($status | table)

    # Test deployment strategy suggestions
    log-info "Testing deployment strategy suggestions..." "test"
    let requirements = {
        regions: ["us-east-1", "eu-west-1"]
        high_availability: true
        cost_optimization: true
    }

    let strategy = (mw_suggest_deployment_strategy $requirements)
    log-info $"Suggested strategy: ($strategy.strategy)" "test"
    log-info $"Primary provider: ($strategy.primary_provider)" "test"
    print $"Rationale: ($strategy.rationale | str join ', ')"

    # Test query servers (this will show the dynamic dispatch in action)
    log-info "Testing server query with dynamic provider dispatch..." "test"
    let query_result = (do {
        mw_query_servers $mock_settings
    } | complete)

    if $query_result.exit_code == 0 {
        log-info $"Query completed, returned ($query_result.stdout | length) results" "test"
    } else {
        log-warning $"Query test failed (expected for mock data): ($query_result.stderr)" "test"
    }
}

# Test multi-provider capabilities
export def test-multi-provider []: nothing -> nothing {
    log-section "Testing Multi-Provider Capabilities" "test"

    # Test provider capabilities comparison
    let providers = ["aws", "upcloud", "local"]

    print "Provider Capabilities Comparison:"
    let capabilities_comparison = ($providers | each {|provider_name|
        let caps = (get-provider-capabilities-for $provider_name)
        {
            provider: $provider_name
            server_management: ($caps.server_management? | default false)
            network_management: ($caps.network_management? | default false)
            auto_scaling: ($caps.auto_scaling? | default false)
            multi_region: ($caps.multi_region? | default false)
            compliance_certs: ($caps.compliance_certifications? | default [] | length)
        }
    })

    print ($capabilities_comparison | table)

    # Show which providers support specific features
    log-info "Providers with auto-scaling:" "test"
    let auto_scaling_providers = ($capabilities_comparison | where auto_scaling == true | get provider)
    print ($auto_scaling_providers | str join ", ")

    log-info "Providers with multi-region support:" "test"
    let multi_region_providers = ($capabilities_comparison | where multi_region == true | get provider)
    print ($multi_region_providers | str join ", ")
}

# Run all tests
export def run-all-tests []: nothing -> nothing {
    log-section "Starting Provider-Agnostic Architecture Tests" "test"

    test-provider-registry
    print ""

    test-provider-loading
    print ""

    test-provider-interface
    print ""

    test-middleware
    print ""

    test-multi-provider
    print ""

    log-success "All tests completed!" "test"
}

# Main entry point
def main [] {
    run-all-tests
}
