#compdef himi

# himi zsh completion
# Drop in ~/.zfunc/ then run: compinit

_himi() {
  local config_dir="${XDG_CONFIG_HOME:-$HOME/.config}/himi"
  local lists_dir="${config_dir}/lists"
  local pool_dir="${config_dir}/pool"

  # Get template names from config
  local -a templates
  if [[ -f "${config_dir}/config.sh" ]]; then
    templates=(${(f)"$(grep -E '^\s*"[a-z]+\|' "${config_dir}/config.sh" 2>/dev/null | sed 's/.*"\([a-z]*\)|.*/\1/')"})
  fi
  [[ ${#templates} -eq 0 ]] && templates=(default easy secure pin diceware)

  # Get list names
  local -a all_lists enabled_lists disabled_lists
  disabled_lists=(all)
  enabled_lists=(all)
  if [[ -d "$lists_dir" ]]; then
    for f in "$lists_dir"/*.txt(N); do
      local name=${${f:t}%.txt}
      all_lists+=($name)
      if [[ -L "$pool_dir/$name.txt" ]]; then
        enabled_lists+=($name)
      else
        disabled_lists+=($name)
      fi
    done
  fi

  local -a commands
  commands=(
    'add:Add and enable a word list'
    'enable:Enable word list(s), or all'
    'disable:Disable word list(s), or all'
    'remove:Delete a word list permanently'
    'rebuild:Rebuild pool from enabled lists'
    'list:Show all lists and status'
    'entropy:Show entropy for templates'
    'test:Test a custom pattern'
    'config:Edit config in $EDITOR'
    'uninstall:Remove himi and all data'
  )

  _arguments -C \
    '1:command:->cmd' \
    '*:argument:->args' \
    '-o[Output to stdout]' \
    '-n[Number of secrets]:count:(1 3 5 10)' \
    '-h[Show help]' \
    '--help[Show help]'

  case "$state" in
    cmd)
      _describe -t commands 'commands' commands
      _describe -t templates 'templates' templates
      ;;
    args)
      case "${words[2]}" in
        add)
          _files -g '*.txt'
          ;;
        enable)
          _describe -t lists 'available lists' disabled_lists
          ;;
        disable)
          _describe -t lists 'enabled lists' enabled_lists
          ;;
        remove)
          _describe -t lists 'available lists' all_lists
          ;;
        entropy)
          _describe -t templates 'templates' templates
          ;;
        test)
          _message 'pattern (e.g. {word}-{num:3})'
          ;;
      esac
      ;;
  esac
}

_himi "$@"
