#!/usr/bin/env nu

# Cross-platform Build Script
# Nushell version of cross-build.sh
# Builds project for different architectures using Docker

def main [] {
    # Configuration - following project's configuration-driven approach
    let docker_image = "localhost/cross-rs/cross-custom-website:x86_64-unknown-linux-gnu-960e8"
    let target_arch = "linux-amd64"
    let current_dir = (pwd)

    print $"(ansi blue)🐳 Cross-building for ($target_arch) using Docker...(ansi reset)"
    print $"(ansi blue)📦 Image: ($docker_image)(ansi reset)"

    # Check if Docker is available
    try {
        docker --version | ignore
    } catch {
        print $"(ansi red)❌ Docker is not available or not running(ansi reset)"
        exit 1
    }

    # Prepare volume mounts
    let project_mount = $"($current_dir):/project"
    let node_modules_mount = $"($current_dir)/node_modules_linux:/project/node_modules"
    let target_mount = $"($current_dir)/target_linux:/project/target"

    print $"(ansi blue)🔧 Setting up Docker environment...(ansi reset)"
    print $"(ansi blue)📁 Project mount: ($project_mount)(ansi reset)"

    # Build command to run inside Docker
    let build_command = "scripts/build/leptos-build.sh && scripts/build/dist-pack.sh linux-amd64"

    # Run Docker command with proper error handling
    try {
        docker run --rm --platform linux/amd64 -v $project_mount -v $node_modules_mount -v $target_mount -w /project $docker_image bash -c $build_command

        print $"(ansi green)✅ Cross-build completed successfully!(ansi reset)"

        # Show result info if dist directory exists
        if ("dist" | path exists) {
            print $"(ansi blue)📦 Distribution files:(ansi reset)"
            ls dist | where name =~ "tar.gz" | each { |file|
                print $"  • ($file.name) - ($file.size)"
            }
        }

    } catch {
        print $"(ansi red)❌ Cross-build failed(ansi reset)"
        print $"(ansi yellow)💡 Check if Docker image exists: ($docker_image)(ansi reset)"
        exit 1
    }
}
