#!/usr/bin/env nu

# Platform compilation module for distribution system
#
# Handles all platform-specific compilation logic including:
# - Rust target triple detection
# - Single platform compilation
# - Parallel and sequential multi-platform compilation
# - Compilation result validation

use std log

# Main compilation orchestrator - delegates to parallel or sequential based on config
export def compile-platforms [config: record]: nothing -> list {
    if $config.parallel_builds {
        compile-platforms-parallel $config
    } else {
        compile-platforms-sequential $config
    }
}

# Compile platforms in parallel
# Note: Current implementation uses sequential compilation
# Future: Can be enhanced with background processes for true parallelization
def compile-platforms-parallel [config: record]: nothing -> list {
    log info "Compiling platforms in parallel mode..."
    compile-platforms-sequential $config
}

# Compile platforms sequentially
# Iterates through each platform and compiles for that target
def compile-platforms-sequential [config: record]: nothing -> list {
    $config.platforms | each {|platform|
        compile-platform $platform $config
    }
}

# Compile platform components for a single platform
# Invokes cargo compilation for the target triple and collects results
export def compile-platform [platform: string, config: record]: nothing -> record {
    log info $"Compiling platform: ($platform)"

    let start_time = (date now)
    let target_triple = get-target-triple $platform

    try {
        # Invoke cargo compilation for the target
        let compile_result = compile-with-cargo $target_triple $config

        # Validate compilation results
        let validation = validate-compilation $compile_result

        {
            platform: $platform
            target: $target_triple
            status: (if $compile_result.failed > 0 { "failed" } else { "success" })
            compiled_components: $compile_result.successful
            total_components: $compile_result.total
            compile_result: $compile_result
            validation: $validation
            duration: ((date now) - $start_time)
        }

    } catch {|err|
        {
            platform: $platform
            target: $target_triple
            status: "failed"
            reason: $err.msg
            duration: ((date now) - $start_time)
        }
    }
}

# Get Rust target triple for a platform name
# Maps common platform names to official Rust target triples
export def get-target-triple [platform: string]: nothing -> string {
    match $platform {
        "linux" => "x86_64-unknown-linux-gnu"
        "macos" => "x86_64-apple-darwin"
        "windows" => "x86_64-pc-windows-gnu"
        _ => $platform  # Assume it's already a target triple
    }
}

# Compile with cargo for a target triple
# Invokes the build compilation tool with appropriate flags
def compile-with-cargo [target: string, config: record]: nothing -> record {
    let start_time = (date now)

    try {
        let compile_result = (nu ($config.repo_root | path join "src" "tools" "build" "compile-platform.nu")
            --target $target
            --release
            --output-dir ($config.output_dir | path join "platform")
            --verbose:$config.verbose
            --clean:$config.build_clean)

        return $compile_result

    } catch {|err|
        {
            failed: 1
            successful: 0
            total: 0
            error: $err.msg
            duration: ((date now) - $start_time)
        }
    }
}

# Validate compilation result structure
# Ensures the result contains expected fields and that compilation succeeded
def validate-compilation [result: record]: nothing -> record {
    let has_required_fields = (
        ($result | has-key "successful") and
        ($result | has-key "total") and
        ($result | has-key "failed")
    )

    let is_valid = (
        $has_required_fields and
        (($result.successful // 0) >= 0) and
        (($result.total // 0) >= 0) and
        (($result.failed // 0) >= 0)
    )

    {
        is_valid: $is_valid
        has_required_fields: $has_required_fields
        compilation_successful: (($result.failed // 1) == 0)
        components_count: ($result.successful // 0)
        total_expected: ($result.total // 0)
    }
}
