#!/usr/bin/env nu

# Orchestrator Plugin Integration Tests
# Tests orchestrator plugin availability, status, tasks, and performance

use std assert

# Test plugin availability
export def test_orch_plugin_available [] {
    print "  Testing orchestrator plugin availability..."

    # Check if orch plugin is registered
    let available = (which orch | length) > 0

    # Should not error
    assert ($available == true or $available == false)

    if $available {
        print "    ✅ Orchestrator plugin is available"
    } else {
        print "    ⚠️  Orchestrator plugin not available (will use HTTP fallback)"
    }
}

# Test status function
export def test_orch_status [] {
    print "  Testing orchestrator status..."

    use orchestrator.nu *

    # Test status check
    let status = (do {
        plugin-orch-status
    } | complete)

    # Should work or fallback gracefully
    if $status.exit_code == 0 {
        print "    ✅ Status check succeeded"
    } else {
        print "    ⚠️  Status check failed (orchestrator might not be running)"
    }
}

# Test tasks function
export def test_orch_tasks [] {
    print "  Testing orchestrator tasks list..."

    use orchestrator.nu *

    # Test tasks list
    let tasks = (do {
        plugin-orch-tasks
    } | complete)

    if $tasks.exit_code == 0 {
        print "    ✅ Tasks list retrieved"
    } else {
        print "    ⚠️  Tasks list failed (orchestrator might not be running)"
    }
}

# Test workflow submission
export def test_workflow_submission [] {
    print "  Testing workflow submission..."

    use orchestrator.nu *

    # Create test workflow
    let workflow = {
        name: "test_workflow"
        operations: []
    }

    let result = (do {
        plugin-orch-submit ($workflow | to json)
    } | complete)

    if $result.exit_code == 0 {
        print "    ✅ Workflow submission succeeded"
    } else {
        print "    ⚠️  Workflow submission failed"
    }
}

# Test workflow status
export def test_workflow_status [] {
    print "  Testing workflow status query..."

    use orchestrator.nu *

    # Test with dummy workflow ID
    let result = (do {
        plugin-orch-workflow-status "test_workflow_id"
    } | complete)

    # Should handle gracefully (might not exist)
    assert ($result.exit_code == 0 or $result.exit_code != 0)
    print "    ✅ Workflow status query working"
}

# Test local vs remote detection
export def test_local_detection [] {
    print "  Testing local vs remote detection..."

    use orchestrator.nu *

    # Test localhost detection
    let is_local_1 = (use-local-plugin "http://localhost:8080")
    assert ($is_local_1 == true)

    let is_local_2 = (use-local-plugin "http://127.0.0.1:8080")
    assert ($is_local_2 == true)

    # Test remote detection
    let is_remote = (use-local-plugin "http://remote.example.com:8080")
    assert ($is_remote == false)

    print "    ✅ Local/remote detection working"
}

# Test health check
export def test_health_check [] {
    print "  Testing orchestrator health check..."

    use orchestrator.nu *

    let health = (do {
        plugin-orch-health
    } | complete)

    if $health.exit_code == 0 {
        print "    ✅ Health check passed"
    } else {
        print "    ⚠️  Health check failed (orchestrator might not be running)"
    }
}

# Test Nickel validation
export def test_nickel_validation [] {
    print "  Testing Nickel validation..."

    use orchestrator.nu *

    # Create simple test Nickel content
    let nickel_content = '''
schema TestSchema:
    name: str
    value: int

config: TestSchema = {
    name = "test"
    value = 42
}
'''

    let result = (do {
        plugin-orch-validate-nickel $nickel_content
    } | complete)

    if $result.exit_code == 0 {
        print "    ✅ Nickel validation succeeded"
    } else {
        print "    ⚠️  Nickel validation failed (might need orchestrator running)"
    }
}

# Test configuration integration
export def test_config_integration [] {
    print "  Testing configuration integration..."

    # Should read orchestrator config values
    let config_check = (do {
        use ../config/accessor.nu *
        get-config-value "plugins.orchestrator.enabled" true
    } | complete)

    assert ($config_check.exit_code == 0)

    # Check data directory config
    let data_dir_check = (do {
        use ../config/accessor.nu *
        get-config-value "plugins.orchestrator.data_dir" "./data"
    } | complete)

    assert ($data_dir_check.exit_code == 0)
    print "    ✅ Configuration integration working"
}

# Performance test
export def test_orch_performance [] {
    print "  Testing orchestrator performance..."

    use orchestrator.nu *

    # Check if plugin is available
    let has_plugin = (which orch | length) > 0

    # Run 5 status check iterations
    let times = (1..5 | each {|_|
        let start = (date now)
        let _ = (plugin-orch-status | complete)
        let end = (date now)
        ($end - $start | into duration | into int) / 1_000_000  # Convert to ms
    })

    let avg_time = ($times | math avg)
    let min_time = ($times | math min)
    let max_time = ($times | math max)

    print $"    Average: ($avg_time)ms, Min: ($min_time)ms, Max: ($max_time)ms"

    if $has_plugin and $avg_time < 10 {
        print "    ✅ Performance excellent (plugin active)"
    } else if $avg_time < 100 {
        print "    ✅ Performance good (likely HTTP fallback)"
    } else {
        print "    ⚠️  Performance slow"
    }
}

# Test error handling
export def test_error_handling [] {
    print "  Testing error handling..."

    use orchestrator.nu *

    # Test with invalid URL
    let result = (do {
        $env.ORCHESTRATOR_URL = "http://invalid-url-that-does-not-exist:99999"
        plugin-orch-status
    } | complete)

    # Should fail gracefully with error message
    if $result.exit_code != 0 {
        assert ($result.stderr | str length) > 0
        print "    ✅ Error handling working correctly"
    } else {
        print "    ⚠️  Expected failure for invalid URL"
    }
}

# Test batch operations
export def test_batch_operations [] {
    print "  Testing batch operations..."

    use orchestrator.nu *

    # Test batch list
    let batch_list = (do {
        plugin-orch-batch-list
    } | complete)

    if $batch_list.exit_code == 0 {
        print "    ✅ Batch list succeeded"
    } else {
        print "    ⚠️  Batch operations not available"
    }
}

# Test statistics
export def test_statistics [] {
    print "  Testing statistics retrieval..."

    use orchestrator.nu *

    let stats = (do {
        plugin-orch-stats
    } | complete)

    if $stats.exit_code == 0 {
        print "    ✅ Statistics retrieved"
    } else {
        print "    ⚠️  Statistics not available"
    }
}

# Main test runner
export def main [] {
    print "\n🧪 Running Orchestrator Plugin Tests...\n"

    test_orch_plugin_available
    test_local_detection
    test_orch_status
    test_health_check
    test_orch_tasks
    test_workflow_submission
    test_workflow_status
    test_batch_operations
    test_statistics
    test_nickel_validation
    test_config_integration
    test_error_handling
    test_orch_performance

    print "\n✅ Orchestrator plugin tests completed!\n"
}
