#!/usr/bin/env nu
# Validate if a command exists in commands-registry.ncl
# Returns: FOUND|true/false or NOT_FOUND
#
# Cache: exports registry to ~/.cache/provisioning/commands-registry.json
# and reuses it until commands-registry.ncl changes (mtime check).
# Typical cold start: ~2s (nickel export). Warm: <50ms (JSON read).

def main [
  command_name: string
]: nothing -> nothing {
  let registry_file = ($env.PROVISIONING | path join "core/nulib/commands-registry.ncl")
  let cache_dir     = ($env.HOME | path join ".cache" | path join "provisioning")
  let cache_file    = ($cache_dir | path join "commands-registry.json")

  # Determine if cache is valid (exists and newer than source)
  let registry_mtime = (ls $registry_file | get 0.modified)
  let use_cache = if ($cache_file | path exists) {
    let cache_mtime = (ls $cache_file | get 0.modified)
    $cache_mtime > $registry_mtime
  } else { false }

  # Load or rebuild
  let registry_json = if $use_cache {
    open --raw $cache_file
  } else {
    let prov = ($env.PROVISIONING? | default "/usr/local/provisioning")
    let result = (do {
      ^nickel export --format json --import-path $prov $registry_file
    } | complete)
    if $result.exit_code != 0 {
      print "ERROR: Failed to export commands-registry.ncl" >&2
      exit 1
    }
    ^mkdir -p $cache_dir
    $result.stdout | save --force $cache_file
    $result.stdout
  }

  let commands = ($registry_json | from json | get -o commands | default [])

  let matches = ($commands | where {|cmd|
    let all = ([$cmd.command] | append ($cmd | get -o aliases | default []))
    $command_name in $all
  })

  if ($matches | is-empty) {
    print "NOT_FOUND"
  } else {
    let m = ($matches | first)
    print $"FOUND|($m | get -o requires_daemon | default false)"
  }
}
