#!/usr/bin/env nu
# test-detect-provctl.nu - Tests for provctl detection functionality
#
# Run with: cargo test --test provisioning_tests
# Or:       nu tests/provisioning/test-detect-provctl.nu

# Test 1: Detect provctl availability
def test_detect_provctl_structure [] {
    let result = (nu scripts/provisioning/detect-provctl.nu)

    # Verify result is a record with expected fields
    assert ($result | type) == "record"
    assert ($result | keys | contains ["available"])
    assert ($result | keys | contains ["path"])
    assert ($result | keys | contains ["version"])

    print "✓ test_detect_provctl_structure passed"
}

# Test 2: Validate result structure when provctl is available
def test_provctl_available_structure [] {
    let result = (nu scripts/provisioning/detect-provctl.nu)

    if ($result.available) {
        assert ($result.path | type) == "string"
        assert ($result.version | type) == "string"
        assert ($result.backends | type) == "list"

        # Path should exist or be in PATH
        assert (($result.path | path exists) or (try { which ($result.path | path basename) } catch { null }) != null)

        print "✓ test_provctl_available_structure passed"
    } else {
        print "⊗ test_provctl_available_structure skipped (provctl not available)"
    }
}

# Test 3: Backends detection
def test_backends_detection [] {
    let result = (nu scripts/provisioning/detect-provctl.nu)

    if ($result.available) {
        # Should have at least pidfile as fallback
        assert ($result.backends | length) > 0
        assert ($result.backends | contains ["pidfile"])

        print "✓ test_backends_detection passed"
    }
}

# Test 4: Verbose output
def test_verbose_output [] {
    # Should not throw error with --verbose flag
    try {
        nu scripts/provisioning/detect-provctl.nu --verbose
        print "✓ test_verbose_output passed"
    } catch { |err|
        print $"✗ test_verbose_output failed: ($err)"
    }
}

# Main test runner
def main [] {
    print ""
    print "Running provctl detection tests..."
    print "────────────────────────────────"

    test_detect_provctl_structure
    test_provctl_available_structure
    test_backends_detection
    test_verbose_output

    print "────────────────────────────────"
    print "✓ All provctl tests completed"
    print ""
}

# Helper: Simple assertion
def assert [condition: bool] {
    if not $condition {
        error make { msg: "Assertion failed" }
    }
}

if ($nu.invocation-dir == (pwd)) {
    main
}
