#!/usr/bin/env nu

# VAPORA Build Script
# Phase 0: Build all workspace crates
# Follows NUSHELL_GUIDELINES.md - 17 rules

# Build a single crate
def build-crate [crate_name: string, release: bool = false]: record {
    print $"Building [$crate_name]..."

    let result = if $release {
        do { cargo build --release -p $crate_name } | complete
    } else {
        do { cargo build -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)
        }
    }
}

# Build all workspace crates
def build-all [release: bool = false]: list {
    let crates = [
        "vapora-shared",
        "vapora-agents",
        "vapora-llm-router",
        "vapora-backend",
        "vapora-frontend",
        "vapora-mcp-server"
    ]

    $crates | each {|crate| build-crate $crate $release }
}

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

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

# Main build function
def main [
    --release = false   # Build in release mode
    --all = false       # Build all crates (default)
    --crate: string = ""  # Build specific crate
]: void {
    print "=== VAPORA Build ==="
    print ""

    let build_mode = if $release { "release" } else { "debug" }
    print $"Build mode: [$build_mode]"
    print ""

    let results = if ($crate != "") {
        [
            (build-crate $crate $release)
        ]
    } else {
        build-all $release
    }

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

    if $success {
        print ""
        print "=== Build Complete ==="
        let success_count = ($results | length)
        print $"✓ ($success_count) crate(s) built successfully"
    } else {
        print ""
        print "Build failed"
        exit 1
    }
}
