#!/usr/bin/env nu
# Thin entry for cluster commands.
# Loads only cluster-deploy.nu + workspace (~140ms vs ~49s for the full entry).
# Bash wrapper routes all cluster subcommands except list (handled by the bash fast-path).

export-env {
    let lib_dirs_raw = ($env.NU_LIB_DIRS? | default "")
    let current_lib_dirs = if ($lib_dirs_raw | type) == "string" {
        if ($lib_dirs_raw | is-empty) { [] } else { ($lib_dirs_raw | split row ":") }
    } else {
        $lib_dirs_raw
    }
    let dynamic = ($env.PROVISIONING? | default "" | path join "core" "nulib")
    $env.NU_LIB_DIRS = ([
        "/opt/provisioning/core/nulib"
        "/usr/local/provisioning/core/nulib"
    ] | append $current_lib_dirs | append (if ($dynamic | is-not-empty) { [$dynamic] } else { [] }))
}

use lib_provisioning/workspace *
use lib_provisioning/user/config.nu [get-workspace-path, get-active-workspace-details]
use main_provisioning/cluster-deploy.nu *

def main [
    ...args: string            # args[0] = "cluster", args[1] = subcommand
    --workspace (-w): string = ""
    --dry-run (-n)
    --kubeconfig (-k): string = ""
    --secrets-file (-s): string = ""
    --debug (-x)
    --notitles
]: nothing -> nothing {
    if $debug { $env.PROVISIONING_DEBUG = true }

    # args[0] = "cluster" (domain), args[1] = subcommand, args[2+] = operands
    let sub     = ($args | get 1? | default "")
    let operands = ($args | skip 2)

    match $sub {
        "deploy" | "d" => {
            let layer   = ($operands | get 0? | default "")
            let cluster = ($operands | get 1? | default "")
            if ($layer | is-empty) or ($cluster | is-empty) {
                print "❌ Usage: provisioning cluster deploy <layer> <cluster> [--workspace <name>]"
                print "   layer:   platform | apps"
                print "   cluster: sgoyol | wuji | ..."
                exit 1
            }
            let ws_arg = if ($workspace | is-not-empty) { $workspace } else { "" }
            if ($ws_arg | is-not-empty) {
                main cluster deploy $layer $cluster --workspace $ws_arg --dry-run=$dry_run --kubeconfig $kubeconfig --secrets-file $secrets_file
            } else {
                main cluster deploy $layer $cluster --dry-run=$dry_run --kubeconfig $kubeconfig --secrets-file $secrets_file
            }
        },

        # list is handled by the bash fast-path (query-clusters.nu), but catch it here too
        "list" | "l" | "" => {
            exec $"($env.PROVISIONING_NAME)" cluster list
        },

        _ => {
            print "Usage: provisioning cluster <subcommand> [options]"
            print ""
            print "  deploy <layer> <cluster> [--workspace <name>] [--dry-run]"
            print "  list"
        },
    }
}
