#!/usr/bin/env nu
# Thin entry for job (orchestrator workflow) commands.
# Loads only workflows/management.nu + auth check helpers as needed.

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 workflows/management.nu *

def main [
    ...args: string
    --orchestrator: string = ""
    --status: string = ""
    --days: int = 7
    --dry-run
    --debug (-x)
]: nothing -> nothing {
    if $debug { $env.PROVISIONING_DEBUG = true }

    let rest = if (($args | length) > 0) and (($args | first) in ["job", "j"]) {
        $args | skip 1
    } else {
        $args
    }
    let sub = ($rest | get 0? | default "list")
    let arg1 = ($rest | get 1? | default "")

    match $sub {
        "list" | "ls" | "l" => {
            let limit_arg = if ($arg1 | is-not-empty) {
                let r = (do { $arg1 | into int } | complete)
                if $r.exit_code == 0 { ($r.stdout | str trim | into int) } else { null }
            } else { null }
            if $limit_arg != null {
                workflow-list --limit $limit_arg --orchestrator $orchestrator --status $status
            } else {
                workflow-list --orchestrator $orchestrator --status $status
            }
        }
        "status" | "st" => {
            if ($arg1 | is-empty) {
                print "Error: job status requires a workflow id"
                return
            }
            workflow-status $arg1 --orchestrator $orchestrator
        }
        "cancel" => {
            if ($arg1 | is-empty) {
                print "Error: job cancel requires a workflow id"
                return
            }
            workflow-cancel $arg1 --orchestrator $orchestrator --dry-run=$dry_run
        }
        "cleanup" => {
            workflow-cleanup --days $days --orchestrator $orchestrator --dry-run=$dry_run
        }
        "help" | "h" | "-h" | "--help" => {
            print "Orchestrator Job Management"
            print "==========================="
            print ""
            print "Usage: prvng job <subcommand> [options]"
            print ""
            print "Subcommands:"
            print "  list [limit]           (alias: ls, l)"
            print "  status <id>            (alias: st)"
            print "  cancel <id>            [--dry-run]"
            print "  cleanup                [--days N] [--dry-run]"
        }
        _ => {
            print $"Unknown job subcommand: ($sub)"
            print "Run: prvng job help"
        }
    }
}
