#!/usr/bin/env nu
# List all available components/taskservs.
# Searches extensions/components/ (flat, primary) then extensions/taskservs/ (grouped, legacy).

use ../lib_provisioning/utils/nickel_processor.nu [ncl-eval-soft]

let provisioning = ($env.PROVISIONING? | default '/usr/local/provisioning')

# Resolve component base path: components/ → taskservs/ (legacy fallback)
let components_base = ($provisioning | path join 'extensions' | path join 'components')
let taskservs_base  = ($provisioning | path join 'extensions' | path join 'taskservs')

mut all_items = []

# Primary: flat components/ (post-migration)
if ($components_base | path exists) {
    for item in (ls $components_base | where type == 'dir') {
        let name  = ($item.name | path basename)
        let meta  = ($item.name | path join 'metadata.ncl')
        let modes = if ($meta | path exists) {
            let result = (ncl-eval-soft $meta [] null)
            if ($result | is-not-empty) { $result | get -o modes | default ['taskserv'] } else { ['taskserv'] }
        } else { ['taskserv'] }
        $all_items = ($all_items | append { task: $name, mode: ($modes | str join ','), info: 'component' })
    }
}

# Legacy: grouped taskservs/ (only if not already found in components/)
if ($taskservs_base | path exists) {
    let known = ($all_items | each {|i| $i.task })
    for cat in (ls $taskservs_base | where type == 'dir') {
        let category = ($cat.name | path basename)
        for ts in (ls $cat.name | where type == 'dir') {
            let ts_name = ($ts.name | path basename)
            if $ts_name not-in $known {
                $all_items = ($all_items | append { task: $ts_name, mode: $category, info: 'taskserv' })
            }
        }
    }
}

if ($all_items | is-empty) {
    print '📦 Available Taskservs: (none found)'
} else {
    print '📦 Available Taskservs:'
    print ''
    $all_items | sort-by task | each {|ts|
        print $"  • ($ts.task) [($ts.mode)]"
    } | ignore
}
