#use ../lib_provisioning/defs/lists.nu providers_list
use ../config/accessor.nu *
use ../utils/nickel_processor.nu [ncl-eval-soft]

export def setup_config_path [
    provisioning_cfg_name: string = "provisioning"
] {
   ($nu.default-config-dir) | path dirname | path join $provisioning_cfg_name
}
export def tools_install [
  tool_name?: string
  run_args?: string
] {
  print $"(_ansi cyan)((get-provisioning-name))(_ansi reset) (_ansi yellow_bold)tools(_ansi reset) check:\n"
  let bin_install = ((get-config-base-path) | path join "core" | path join "bin" | path join "tools-install")
  if not ($bin_install | path exists) {
    print $"🛑 Error running (_ansi yellow)tools_install(_ansi reset) not found (_ansi red_bold)($bin_install | path basename)(_ansi reset)"
    if (is-debug-enabled) { print $"($bin_install)" }
    return false
  }
  let res = (^$"($bin_install)" $run_args $tool_name | complete)
  if ($res.exit_code == 0 ) {
    print $res.stdout
    true
  } else {
    print $"🛑 Error running (_ansi yellow)tools-install(_ansi reset) (_ansi red_bold)($bin_install | path basename)(_ansi reset)\n($res.stdout)"
    if (is-debug-enabled) { print $"($bin_install)" }
    false
  }
}
export def providers_install [
  prov_name?: string
  run_args?: string
] {
  let providers_path = (get-providers-path)
  if not ($providers_path | path exists) { return }
  providers_list "full" | each {|prov|
    let name = ($prov | get name? | default "")
    if ($prov_name | is-empty) or $prov_name == $name {
      let bin_install = ($providers_path | path join $name | path join "bin" | path join "install.sh" )
      if ($bin_install | path exists) {
        let res = (^$"($bin_install)" $run_args | complete)
        if ($res.exit_code != 0 ) {
          print ($"🛑 Error running (_ansi yellow)($name)(_ansi reset) (_ansi red_bold)($bin_install | path basename)(_ansi reset)\n($res.stdout)")
          if (is-debug-enabled) { print $"($bin_install)" }
        } else {
          print -n $"(_ansi green)($name)(_ansi reset) tools:"
          print ($prov | get tools? | default "")
          print ""
          if ($res.exit_code == 0 ) {
            _print $res.stdout
          }
        }
      }
    }
  }
}
export def create_versions_file [
  targetname: string = "versions"
] {
  let target_name = if ($targetname | is-empty) { "versions" } else { $targetname }
  let provisioning_base = ($env.PROVISIONING? | default (get-config-base-path))
  let versions_ncl = ($provisioning_base | path join "core" | path join "versions.ncl")
  let versions_target = ($provisioning_base | path join "core" | path join $target_name)
  let providers_path = ($provisioning_base | path join "extensions" | path join "providers")

  # Check if versions.ncl exists
  if not ($versions_ncl | path exists) {
    return false
  }

  # Generate KEY="VALUE" format
  mut content = ""

  # ============================================================================
  # CORE TOOLS
  # ============================================================================
  let json_data = (ncl-eval-soft $versions_ncl [] null)

  if $json_data != null {
    let core_versions = ($json_data | get core_versions? | default [])

    for item in $core_versions {
      let name = ($item | get name?)
      let version_obj = ($item | get version?)

      if ($name | is-not-empty) and ($version_obj | is-not-empty) {
        let key = ($name | str upcase)
        let current = ($version_obj | get current?)
        let source = ($version_obj | get source?)

        $content += $"($key)_VERSION=\"($current)\"\n"
        $content += $"($key)_SOURCE=\"($source)\"\n"

        # Add short aliases for common bash scripts (e.g., nushell -> NU)
        let short_key = if $name == "nushell" {
          "NU"
        } else if $name == "nickel" {
          "NICKEL"
        } else if $name == "sops" {
          "SOPS"
        } else if $name == "age" {
          "AGE"
        } else if $name == "k9s" {
          "K9S"
        } else {
          ""
        }

        if ($short_key | is-not-empty) and ($short_key != $key) {
          $content += $"($short_key)_VERSION=\"($current)\"\n"
          $content += $"($short_key)_SOURCE=\"($source)\"\n"
        }

        $content += "\n"
      }
    }
  }

  # ============================================================================
  # PROVIDERS
  # ============================================================================
  if ($providers_path | path exists) {
    for provider_item in (ls $providers_path) {
      let provider_dir = ($providers_path | path join $provider_item.name)
      let provider_version_file = ($provider_dir | path join "nickel" | path join "version.ncl")

      if ($provider_version_file | path exists) {
        let provider_data = (ncl-eval-soft $provider_version_file [] null)

        if $provider_data != null {
          let prov_name = ($provider_data | get name?)
          let prov_version_obj = ($provider_data | get version?)

          if ($prov_name | is-not-empty) and ($prov_version_obj | is-not-empty) {
            let prov_key = $"PROVIDER_($prov_name | str upcase)"
            let prov_current = ($prov_version_obj | get current?)
            let prov_source = ($prov_version_obj | get source?)

            $content += $"($prov_key)_VERSION=\"($prov_current)\"\n"
            $content += $"($prov_key)_SOURCE=\"($prov_source)\"\n"
            $content += "\n"
          }
        }
      }
    }
  }

  # Save to file
  if ($content | is-not-empty) {
    $content | save --force $versions_target
    true
  } else {
    false
  }
}
