# Build command handler — directly invoke image subcommand handlers

export def handle_build_command [command: string, ops: string, flags: record] {
    use ../../images/create.nu *
    use ../../images/list.nu *
    use ../../images/update.nu *
    use ../../images/delete.nu *
    use ../../images/state.nu *
    use ../../images/watch.nu *

    # Normalize: strip leading "image " prefix when invoked via "build build" registry path
    let image_ops = if $command == "build" {
        if ($ops | str starts-with "image ") {
            $ops | str replace "image " ""
        } else {
            if ($ops | str trim) == "image" {
                "help"
            } else {
                if ($ops | is-empty) { "help" } else { $ops }
            }
        }
    } else {
        # command == "image" from "bi" / "build-image" shortcut
        if ($ops | is-empty) { "help" } else { $ops }
    }

    # Parse the image_ops to extract subcommand and role
    let parts = ($image_ops | split row " ")
    let subcommand = if ($parts | length) > 0 { $parts | get 0 } else { "help" }
    let role = if ($parts | length) > 1 { $parts | get 1 } else { "" }

    # Extract flag values
    let check_f = ($flags | get check_mode? | default false)
    let yes_f = ($flags | get auto_confirm? | default false)
    let infra_f = ($flags.infra? | default "")
    let provider_f = ($flags.provider? | default "")

    # Call the appropriate image subcommand handler
    match $subcommand {
        "create" | "c" => {
            image-create $role --infra=$infra_f --check=$check_f
        }
        "list" | "l" => {
            image-list --provider=$provider_f
        }
        "update" | "u" => {
            image-update $role --infra=$infra_f --check=$check_f
        }
        "delete" | "d" => {
            image-delete $role --yes=$yes_f
        }
        "state" | "s" => {
            image-state-list --provider=$infra_f
        }
        "watch" | "w" => {
            image-watch --interval=(($role | into int) | default 30)
        }
        "help" | "h" | _ => {
            print "Image Management Commands"
            print "======================="
            print ""
            print "Usage: provisioning build image <command> [options]"
            print ""
            print "Commands:"
            print "  create <role>     - Build snapshot for role"
            print "  list              - Show all role states"
            print "  update <role>     - Rebuild stale snapshot"
            print "  delete <role>     - Remove snapshot + state"
            print "  state             - List all state files"
            print "  watch             - Monitor role freshness"
            print ""
            print "Options:"
            print "  --infra <path>    - Infrastructure directory"
            print "  --check           - Validate without executing"
            print "  --yes             - Skip confirmation"
            print ""
        }
    }
}
