# Module: Utilities Command Dispatcher
# Purpose: Routes utility commands (SSH, SOPS, cache, providers, plugins, guides) to appropriate handlers.
# Dependencies: utilities_handlers

# Utility Command Core - Main dispatcher
# Handles routing to: ssh, sed, sops, cache, providers, nu, list, qr

use ../flags.nu *
# REMOVED: use ../../lib_provisioning * - causes circular import
use ../../servers/ssh.nu *
use ../../servers/utils.nu *

# Import all handler functions
use ./utilities_handlers.nu *

# Helper to run module commands
def run_module [
  args: string
  module: string
  option?: string
  --exec
] {
  let use_debug = if ($env.PROVISIONING_DEBUG? | default false) { "-x" } else { "" }

  if $exec {
    exec $"($env.PROVISIONING_NAME)" $use_debug -mod $module ($option | default "") $args
  } else {
    ^$"($env.PROVISIONING_NAME)" $use_debug -mod $module ($option | default "") $args
  }
}

# Main utility command dispatcher
export def handle_utility_command [
  command: string
  ops: string
  flags: record
] {
  match $command {
    "ssh" => { handle_ssh $flags }
    "sed" | "sops" => { handle_sops_edit $command $ops $flags }
    "cache" => { handle_cache $ops $flags }
    "providers" => { handle_providers $ops $flags }
    "nu" => { handle_nu $ops $flags }
    "list" | "l" | "ls" => { handle_list $ops $flags }
    "qr" => { handle_qr }
    "nuinfo" => { handle_nuinfo }
    "plugin" | "plugins" => { handle_plugins $ops $flags }
    "guide" | "guides" | "howto" => { handle_guide $ops $flags }
    _ => {
      print $"❌ Unknown utility command: ($command)"
      print ""
      print "Available utility commands:"
      print "  ssh       - SSH into server"
      print "  sed       - Edit SOPS encrypted files (alias)"
      print "  sops      - Edit SOPS encrypted files"
      print "  cache     - Cache management (status, config, clear, list)"
      print "  providers - List available providers"
      print "  nu        - Start Nushell with provisioning library loaded"
      print "  list      - List resources (servers, taskservs, clusters)"
      print "  qr        - Generate QR code"
      print "  nuinfo    - Show Nushell version info"
      print "  plugin    - Plugin management (list, register, test, status)"
      print "  guide     - Show interactive guides (from-scratch, update, customize)"
      print ""
      print "Use 'provisioning help utilities' for more details"
      exit 1
    }
  }
}
