

use ../lib_provisioning/utils/ssh.nu *
use ../lib_provisioning/defs/lists.nu *
use ../lib_provisioning/config/accessor.nu *
# REMOVED: use lib_provisioning * - causes circular import
# Resolve taskserv/component library directory.
# Search order:
#   1. Flat: taskservs_path/{name}/ (covers components/ and old flat taskservs/)
#   2. Grouped: taskservs_path/{category}/{name}/ (old grouped taskservs/ structure)
#   3. Components sibling: ../components/{name}/ (when called with taskservs/ that no longer exists)
# Returns the directory containing the taskserv, or "" if not found.
export def find-taskserv-dir [taskservs_path: string, name: string]: nothing -> string {
    let direct = ($taskservs_path | path join $name)
    if ($direct | path exists) { return $direct }
    # Try components/ sibling before scanning category subdirs (handles post-migration case)
    let components_sibling = ($taskservs_path | path dirname | path join "components" | path join $name)
    if ($components_sibling | path exists) { return $components_sibling }
    if not ($taskservs_path | path exists) { return "" }
    let candidate = (do -i { ls $taskservs_path }
        | where type == "dir"
        | each {|cat|
            let p = ($cat.name | path join $name)
            if ($p | path exists) { $p } else { null }
        }
        | compact)
    if ($candidate | is-empty) { "" } else { $candidate | first }
}

export def taskserv_get_file [
    settings: record
    taskserv: record
    server: record
    live_ip: string
    req_sudo: bool
    local_mode: bool
] {
    let target_path = ($taskserv.target_path | default "")
    if $target_path == "" {
        _print $"🛑 No (_ansi red_bold)target_path(_ansi reset) found in ($server.hostname) taskserv ($taskserv.name)"
        return false
    }
    let source_path = ($taskserv.soruce_path | default "")
    if $source_path == ""  {
        _print $"🛑 No (_ansi red_bold)source_path(_ansi reset) found in ($server.hostname) taskserv ($taskserv.name)"
        return false
    }
    if $local_mode {
        let res = (^cp $source_path $target_path | combine)
        if $res.exit_code != 0 {
            _print $"🛑 Error get_file [ local-mode ] (_ansi red_bold)($source_path) to ($target_path)(_ansi reset) in ($server.hostname) taskserv ($taskserv.name)"
            _print $res.stdout
            return false
        }
        return true
    }
    let ip = if $live_ip != ""  {
        $live_ip
    } else {
        #use ../../../providers/prov_lib/middleware.nu mw_get_ip
        (mw_get_ip $settings $server ($server | get -o liveness_ip | default "public") false)
    }
    let ssh_key_path = ($server.ssh_key_path | default "")
    if $ssh_key_path == ""  {
        _print $"🛑 No (_ansi red_bold)ssh_key_path(_ansi reset) found in ($server.hostname) taskserv ($taskserv.name)"
        return false
    }
    if not ($ssh_key_path | path exists)  {
        _print $"🛑 Error (_ansi red_bold)($ssh_key_path)(_ansi reset) not found for ($server.hostname) taskserv ($taskserv.name)"
        return false
    }
    mut cmd = if $req_sudo { "sudo" } else { "" }
    let wk_path = $"/home/($env.SSH_USER)/($source_path | path basename)"
    $cmd = $"($cmd) cp ($source_path) ($wk_path); sudo chown ($env.SSH_USER) ($wk_path)"
    let res = (ssh_cmd $settings $server false $cmd $ip)
    if not $res { return false }
    if not (scp_from $settings $server $wk_path $target_path $ip ) {
        return false
    }
    let rm_cmd = if $req_sudo {
        $"sudo rm -f ($wk_path)"
    } else {
        $"rm -f ($wk_path)"
    }
    return ( ssh_cmd $settings $server false $rm_cmd $ip )
}

export def find_taskserv [
    settings: record,
    server: record,
    taskserv_name: string,
    out: string
] {
    let taskservs_list = ($server | get taskservs? | default [])
    let taskserv = ($taskservs_list | where {|t| ($t | get name? | default "") == $taskserv_name})
    if ($taskserv | is-empty) {
        _print $"🛑 No taskserv found" $"for (_ansi yellow_bold)($taskserv_name)(_ansi reset)"
        return ""
    }
    let src_path = ($settings | get src_path? | default "")
    let hostname = ($server | get hostname? | default "")
    let run_taskservs_path = (get-run-taskservs-path)
    mut taskserv_host_path = ($src_path | path join $run_taskservs_path |
        path join $hostname | path join $"($taskserv_name).ncl")
    let def_taskserv = if ($taskserv_host_path | path exists) {
        (open -r $taskserv_host_path)
    } else {
        $taskserv_host_path = ($src_path | path join $run_taskservs_path | path join $"($taskserv_name).ncl")
        if ($taskserv_host_path | path exists) {
            (open -r $taskserv_host_path)
        } else {
            _print $"🛑 No taskserv path found" $"for (_ansi yellow_bold)($taskserv_name)(_ansi reset) in ($taskserv_host_path)"
            $taskserv_host_path = ""
            ""
        }
    }
    let taskservs_path = (get-taskservs-path)
    mut main_taskserv_path = ($taskservs_path | path join $taskserv_name | path join "nickel" | path join $"($taskserv_name).ncl")
    if not ($main_taskserv_path | path exists) {
        $main_taskserv_path = ($taskservs_path | path join $taskserv_name | path join ($taskserv |
        get -o profile | default "") | path join "nickel" | path join $"($taskserv_name).ncl")
    }
    let def_main = if ($main_taskserv_path | path exists) {
        (open -r $main_taskserv_path)
    } else {
        _print $"🛑 No taskserv main path found" $"for (_ansi yellow_bold)($taskserv_name)(_ansi reset) ($main_taskserv_path)"
        $main_taskserv_path = ""
        ""
    }
    { path_def: $taskserv_host_path, def: $def_taskserv, path_main: $main_taskserv_path, main: $def_main }
}
export def list_taskservs [
    settings: record
] {
    let list_taskservs = (taskservs_list)
    if ($list_taskservs | length) == 0 {
        _print $"🛑 no items found for (_ansi cyan)taskservs list(_ansi reset)"
        return
    }
    $list_taskservs
}
