#!/usr/bin/env nu

# VAPORA Docker Build Script
# Builds all Docker images for VAPORA v2.0

def main [
    --registry: string = "docker.io"  # Docker registry
    --tag: string = "latest"  # Image tag
    --push  # Push images to registry after build
    --no-cache  # Build without cache
] {
    print $"(ansi green)🐳 VAPORA Docker Build Script(ansi reset)"
    print $"(ansi blue)═══════════════════════════════════════════════(ansi reset)"
    print $"Registry: ($registry)"
    print $"Tag:      ($tag)"
    print $"Push:     ($push)"
    print ""

    # Define images
    let images = [
        {
            name: "vapora/backend"
            dockerfile: "crates/vapora-backend/Dockerfile"
            context: "."
        }
        {
            name: "vapora/frontend"
            dockerfile: "crates/vapora-frontend/Dockerfile"
            context: "."
        }
        {
            name: "vapora/agents"
            dockerfile: "crates/vapora-agents/Dockerfile"
            context: "."
        }
        {
            name: "vapora/mcp-server"
            dockerfile: "crates/vapora-mcp-server/Dockerfile"
            context: "."
        }
    ]

    # Build each image
    for image in $images {
        print $"(ansi yellow)🔨 Building ($image.name):($tag)...(ansi reset)"

        let full_tag = $"($registry)/($image.name):($tag)"
        let build_args = [
            "build"
            "-f" $image.dockerfile
            "-t" $full_tag
            $image.context
        ]

        let build_args = if $no_cache {
            $build_args | append ["--no-cache"]
        } else {
            $build_args
        }

        try {
            docker ...$build_args
            print $"(ansi green)✅ Built ($image.name):($tag)(ansi reset)"
        } catch {
            print $"(ansi red)❌ Failed to build ($image.name)(ansi reset)"
            exit 1
        }

        # Push if requested
        if $push {
            print $"(ansi cyan)📤 Pushing ($full_tag)...(ansi reset)"
            try {
                docker push $full_tag
                print $"(ansi green)✅ Pushed ($full_tag)(ansi reset)"
            } catch {
                print $"(ansi red)❌ Failed to push ($full_tag)(ansi reset)"
                exit 1
            }
        }

        print ""
    }

    print $"(ansi green)✅ All images built successfully!(ansi reset)"

    if $push {
        print $"(ansi green)✅ All images pushed to registry!(ansi reset)"
    } else {
        print $"(ansi yellow)💡 Tip: Use --push to push images to registry(ansi reset)"
    }

    print ""
    print $"(ansi cyan)Built images:(ansi reset)"
    for image in $images {
        print $"  • ($registry)/($image.name):($tag)"
    }
}
