#! /bin/bash

#######################################
#
# Globals:
#   COMPREPLY
#   COMP_CWORD
#   COMP_WORDS
# Arguments:
#  None
#######################################
function _winget() {

  local cur=${COMP_WORDS[COMP_CWORD]}
  local prev=${COMP_WORDS[COMP_CWORD - 1]}

  case "$prev" in
  install | show | search)
    local program_list
    program_list="$(winpwsh-exe winget search "${cur}" | sed -z "s/\r/ /g" | tr '[:upper:]' '[:lower:]')"
    mapfile -t COMPREPLY < <(compgen -W "$program_list" -- "${cur,,}" )
    ;;
  # validate command and its specific options (-m, --manifest)
  validate | -m | --manifest)
    mapfile -t COMPREPLY < <(compgen -f -X '!*.yml' -- "${cur}")
    ;;
  *)
    # General commands and options (updated for v1.12.350)
    mapfile -t COMPREPLY < <(compgen -W "install show source search list ls upgrade uninstall hash validate settings features export import \
                                pin configure download repair dscv3 mcp \
                                -v --version --info --help -? \
                                --wait --logs --open-logs --verbose --verbose-logs --nowarn --ignore-warnings --disable-interactivity --proxy --no-proxy -m --manifest" -- "${cur}")
    ;;
    #   Generate the completion matches and load them into $COMPREPLY array.
  esac

  return 0
}

complete -F _winget winget
