#!/usr/bin/env nu

# VAPORA Test Script
# Phase 0: Run tests for all workspace crates
# Follows NUSHELL_GUIDELINES.md - 17 rules

# Run tests for a single crate
def test-crate [crate_name: string]: record {
    print $"Testing [$crate_name]..."

    let result = (do { cargo test -p $crate_name } | complete)

    if ($result.exit_code == 0) {
        {
            crate: $crate_name,
            success: true,
            error: null
        }
    } else {
        {
            crate: $crate_name,
            success: false,
            error: ($result.stderr | str trim)
        }
    }
}

# Run tests for all workspace crates
def test-all []: list {
    let crates = [
        "vapora-shared",
        "vapora-agents",
        "vapora-llm-router",
        "vapora-backend",
        "vapora-mcp-server"
    ]

    $crates | each {|crate| test-crate $crate }
}

# Check if all tests passed
def check-test-results [results: list]: bool {
    let failures = ($results | where {|r| not $r.success })

    if (($failures | length) > 0) {
        print ""
        print "=== Test Failures ==="
        for failure in $failures {
            print $"✗ ($failure.crate): ($failure.error)"
        }
        false
    } else {
        true
    }
}

# Run workspace-wide tests
def test-workspace []: record {
    print "Running workspace tests..."

    let result = (do { cargo test --workspace } | complete)

    if ($result.exit_code == 0) {
        {
            success: true,
            error: null
        }
    } else {
        {
            success: false,
            error: ($result.stderr | str trim)
        }
    }
}

# Main test function
def main [
    --all = false         # Test all crates individually
    --workspace = false   # Test entire workspace
    --crate: string = ""  # Test specific crate
]: void {
    print "=== VAPORA Test Suite ==="
    print ""

    let results = if ($crate != "") {
        # Test specific crate
        [
            (test-crate $crate)
        ]
    } else if $workspace {
        # Test entire workspace
        let ws_result = (test-workspace)
        if $ws_result.success {
            print ""
            print "=== All Tests Passed ==="
            print "✓ Workspace tests completed"
            return
        } else {
            print ""
            print $"ERROR: ($ws_result.error)"
            exit 1
        }
    } else {
        # Test all crates individually
        test-all
    }

    # Check results
    print ""
    let success = (check-test-results $results)

    if $success {
        print ""
        print "=== All Tests Passed ==="
        let test_count = ($results | length)
        print $"✓ ($test_count) crate(s) tested successfully"
    } else {
        print ""
        print "Tests failed"
        exit 1
    }
}
