#!/usr/bin/env zsh

__import "core/core"

local    arg
local -a cmds user_cmds

user_cmds=( ${^path}/zplug-*(N-.:t:gs:zplug-:) )

arg="$1"
case "$arg" in
    "")
        __zplug::print::print::die \
            "[zplug] too few arguments\n"
        return 1
        ;;
esac

# User-defined command
if [[ -n ${(M)user_cmds:#$arg} ]]; then
    eval "$commands[zplug-$arg]"
    return $status
fi

# Auto correct like git(1)
__zplug::core::core::get_autoload_files \
    "$ZPLUG_ROOT/autoload/commands"
reply+=("${user_cmds[@]}")

cmds=(
${(@f)"$(awk \
    -f "$ZPLUG_ROOT/misc/share/fuzzy.awk" \
    -v search_string="$arg" \
    <<<"${(F)reply:gs:_:}"
)"}
)

case $#cmds in
    0)
        __zplug::print::print::die \
            "[zplug] $arg: no such command\n"
        return 1
        ;;
    1)
        __zplug::print::print::die \
            "[zplug] $fg[red]${(%):-"%U"}WARNING${(%):-"%u"}$reset_color: "
        __zplug::print::print::die \
            "You called a zplug command named '%s', which does not exist.\n" \
            "$arg"
        __zplug::print::print::die \
            "        Continuing under the assumption that you meant '$fg[green]%s$reset_color'.\n" \
            "$cmds"
        shift
        zplug "$cmds" ${1:+"$@"}
        return $status
        ;;
    *)
        __zplug::print::print::die \
            "[zplug] '%s' is not a zplug command. See 'zplug help'.\n" "$arg"
        __zplug::print::print::die \
            "        Did you mean one of these?\n"
        __zplug::print::print::die \
            "               %s\n" ${cmds}
        return 1
        ;;
esac
