#!/usr/bin/env nu

# Test Setup Validation Script
# Verifies that all plugin tests are properly configured and ready to run

# Color codes
const GREEN = "\e[32m"
const YELLOW = "\e[33m"
const RED = "\e[31m"
const CYAN = "\e[36m"
const RESET = "\e[0m"

# Print colored message
def print_color [color: string, message: string] {
    print $"($color)($message)($RESET)"
}

# Check if file exists
def check_file [path: string, description: string] {
    let exists = ($path | path exists)
    if $exists {
        print_color $GREEN $"  ✅ ($description): ($path)"
    } else {
        print_color $RED $"  ❌ ($description) MISSING: ($path)"
    }
    $exists
}

# Check if file contains expected content
def check_content [path: string, pattern: string, description: string] {
    if not ($path | path exists) {
        print_color $RED $"  ❌ ($description): File not found"
        return false
    }

    let content = (open $path)
    let found = ($content | str contains $pattern)

    if $found {
        print_color $GREEN $"  ✅ ($description): Pattern found"
    } else {
        print_color $YELLOW $"  ⚠️  ($description): Pattern not found"
    }
    $found
}

# Main validation
export def main [] {
    print_color $CYAN "\n🔍 Validating Plugin Test Setup\n"
    let separator = (0..69 | each {|_| "=" } | str join "")
    print_color $CYAN $separator

    mut all_ok = true

    # ============================================================================
    # Check Test Files
    # ============================================================================
    print_color $CYAN "📝 Checking Test Files:"
    let test_files = [
        "../lib_provisioning/plugins/auth_test.nu"
        "../lib_provisioning/plugins/kms_test.nu"
        "../lib_provisioning/plugins/orchestrator_test.nu"
        "./test_plugin_integration.nu"
        "./run_plugin_tests.nu"
    ]

    for file in $test_files {
        let ok = (check_file $file $"Test file")
        $all_ok = $all_ok and $ok
    }

    # ============================================================================
    # Check Configuration Files
    # ============================================================================
    print ""
    print_color $CYAN "⚙️  Checking Configuration Files:"

    let config_ok = (check_file
        "../../../config/plugin-config.toml"
        "Plugin configuration"
    )
    $all_ok = $all_ok and $config_ok

    # ============================================================================
    # Check Documentation
    # ============================================================================
    print ""
    print_color $CYAN "📚 Checking Documentation:"

    let doc_ok = (check_file
        "./PLUGIN_TEST_README.md"
        "Test documentation"
    )
    $all_ok = $all_ok and $doc_ok

    # ============================================================================
    # Check CI/CD Configuration
    # ============================================================================
    print ""
    print_color $CYAN "🚀 Checking CI/CD Configuration:"

    let ci_ok = (check_file
        "../../../../.github/workflows/plugin-tests.yml"
        "GitHub Actions workflow"
    )
    $all_ok = $all_ok and $ci_ok

    # ============================================================================
    # Validate Test Content
    # ============================================================================
    print ""
    print_color $CYAN "🔬 Validating Test Content:"

    # Auth tests
    let auth_ok = (check_content
        "../lib_provisioning/plugins/auth_test.nu"
        "export def main"
        "Auth test main function"
    )
    $all_ok = $all_ok and $auth_ok

    # KMS tests
    let kms_ok = (check_content
        "../lib_provisioning/plugins/kms_test.nu"
        "test_encrypt_decrypt_roundtrip"
        "KMS round-trip test"
    )
    $all_ok = $all_ok and $kms_ok

    # Orchestrator tests
    let orch_ok = (check_content
        "../lib_provisioning/plugins/orchestrator_test.nu"
        "test_orch_status"
        "Orchestrator status test"
    )
    $all_ok = $all_ok and $orch_ok

    # Integration tests
    let integration_ok = (check_content
        "./test_plugin_integration.nu"
        "test_auth_workflow"
        "Auth workflow test"
    )
    $all_ok = $all_ok and $integration_ok

    # ============================================================================
    # Check Plugin Availability
    # ============================================================================
    print ""
    print_color $CYAN "🔌 Checking Plugin Availability:"

    let auth_plugin = (which auth | length) > 0
    let kms_plugin = (which kms | length) > 0
    let orch_plugin = (which orch | length) > 0

    if $auth_plugin {
        print_color $GREEN "  ✅ Auth plugin is available"
    } else {
        print_color $YELLOW "  ⚠️  Auth plugin not available (HTTP fallback will be used)"
    }

    if $kms_plugin {
        print_color $GREEN "  ✅ KMS plugin is available"
    } else {
        print_color $YELLOW "  ⚠️  KMS plugin not available (SOPS fallback will be used)"
    }

    if $orch_plugin {
        print_color $GREEN "  ✅ Orchestrator plugin is available"
    } else {
        print_color $YELLOW "  ⚠️  Orchestrator plugin not available (HTTP fallback will be used)"
    }

    # ============================================================================
    # Check Nushell Version
    # ============================================================================
    print ""
    print_color $CYAN "🐚 Checking Nushell Environment:"

    let nu_version = (version | get version)
    print $"  • Nushell version: ($nu_version)"

    let version_parts = ($nu_version | split row ".")
    let major = ($version_parts | first | into int)
    let minor = ($version_parts | get 1 | into int)

    if $major == 0 and $minor >= 107 {
        print_color $GREEN "  ✅ Nushell version is compatible (>=0.107)"
    } else {
        print_color $RED "  ❌ Nushell version too old (need >=0.107)"
        $all_ok = false
    }

    # ============================================================================
    # Test Execution Validation
    # ============================================================================
    print ""
    print_color $CYAN "🧪 Testing Test Execution:"

    # Try to run a simple test
    let test_result = (do {
        nu ../lib_provisioning/plugins/auth_test.nu
    } | complete)

    if $test_result.exit_code == 0 {
        print_color $GREEN "  ✅ Sample test executed successfully"
    } else {
        print_color $YELLOW "  ⚠️  Sample test had issues (might be expected if services unavailable)"
        print $"    Exit code: ($test_result.exit_code)"
    }

    # ============================================================================
    # Configuration Validation
    # ============================================================================
    print ""
    print_color $CYAN "⚙️  Validating Configuration:"

    if ("../../../config/plugin-config.toml" | path exists) {
        let config = (open ../../../config/plugin-config.toml)

        # Check key configuration sections
        if ($config | get plugins.enabled? | default false) {
            print_color $GREEN "  ✅ Plugins globally enabled"
        } else {
            print_color $YELLOW "  ⚠️  Plugins globally disabled"
        }

        if ($config | get plugins.auth.enabled? | default false) {
            print_color $GREEN "  ✅ Auth plugin enabled in config"
        }

        if ($config | get plugins.kms.enabled? | default false) {
            print_color $GREEN "  ✅ KMS plugin enabled in config"
        }

        if ($config | get plugins.orchestrator.enabled? | default false) {
            print_color $GREEN "  ✅ Orchestrator plugin enabled in config"
        }
    }

    # ============================================================================
    # Final Report
    # ============================================================================
    print ""
    let separator = (0..69 | each {|_| "=" } | str join "")
    print_color $CYAN $separator

    if $all_ok {
        print_color $GREEN "\n✅ All validation checks passed!"
        print_color $GREEN "   Plugin test suite is ready to run.\n"
        print "Quick start:"
        print "  nu run_plugin_tests.nu\n"
        exit 0
    } else {
        print_color $RED "\n❌ Some validation checks failed!"
        print_color $YELLOW "   Tests may still work with fallback mode.\n"
        print "To fix issues:"
        print "  1. Ensure all test files are present"
        print "  2. Install plugins if needed"
        print "  3. Check configuration files\n"
        exit 1
    }
}
