# Completion behavior and wrapper bindings

autoload -Uz add-zsh-hook

if ! whence -w compdef >/dev/null 2>&1; then
    autoload -Uz compinit
    if [ -n "${ZSH_COMPDUMP:-}" ]; then
        mkdir -p "${ZSH_COMPDUMP:h}"
        if [ -f "$ZSH_COMPDUMP" ]; then
            compinit -C -d "$ZSH_COMPDUMP" >/dev/null 2>&1
        else
            compinit -i -d "$ZSH_COMPDUMP" >/dev/null 2>&1
        fi
    else
        compinit -i >/dev/null 2>&1
    fi
fi

zmodload zsh/complist 2>/dev/null || true

zstyle ':completion:*' menu select
zstyle ':completion:*' verbose yes
zstyle ':completion:*' list-grouped yes
zstyle ':completion:*' use-cache yes
zstyle ':completion:*:descriptions' format '%F{240}%B%d%b%f'

typeset -ga DOTZSH_USED_COMMANDS
typeset -ga DOTZSH_ALL_COMMANDS
typeset -gA DOTZSH_USED_COMMAND_MAP
typeset -gA DOTZSH_ALL_COMMAND_MAP
typeset -g DOTZSH_USED_COMMANDS_INITIALIZED=0
typeset -g DOTZSH_ALL_COMMANDS_INITIALIZED=0
typeset -g DOTZSH_USED_COMMAND_LIMIT=120

_dotzsh_parse_history_line() {
    local raw_line="$1"
    local parsed_line="$raw_line"

    case "$parsed_line" in
        ': '*';'*)
            parsed_line="${parsed_line#*;}"
            ;;
    esac

    print -r -- "$parsed_line"
}

_dotzsh_extract_command_name() {
    local line="$(_dotzsh_parse_history_line "$1")"
    local command_name=""
    local -a parts=()
    local index=1

    [ -n "$line" ] || return 1
    [[ "$line" == '#'* ]] && return 1

    parts=(${(z)line})
    [ "${#parts[@]}" -gt 0 ] || return 1

    while [ "$index" -le "${#parts[@]}" ]; do
        command_name="${parts[$index]}"

        case "$command_name" in
            sudo|time|command|builtin|noglob|env)
                ((index++))
                continue
                ;;
            *=*)
                ((index++))
                continue
                ;;
        esac

        break
    done

    [ -n "$command_name" ] || return 1
    [[ "$command_name" == _* ]] && return 1
    [[ "$command_name" =~ '^[A-Za-z0-9][A-Za-z0-9+._-]*$' ]] || return 1

    print -r -- "$command_name"
}

_dotzsh_remember_command() {
    local command_name="$1"

    [ -n "$command_name" ] || return 0

    DOTZSH_USED_COMMANDS=(${DOTZSH_USED_COMMANDS:#$command_name})
    DOTZSH_USED_COMMANDS=("$command_name" "${DOTZSH_USED_COMMANDS[@]}")
    DOTZSH_USED_COMMAND_MAP[$command_name]=1
}

_dotzsh_initialize_used_commands() {
    local history_file="${HISTFILE:-$HOME/.zsh_history}"
    local line=""
    local command_name=""

    [ "$DOTZSH_USED_COMMANDS_INITIALIZED" -eq 0 ] || return 0

    DOTZSH_USED_COMMANDS=()
    DOTZSH_USED_COMMAND_MAP=()

    while IFS= read -r line; do
        command_name="$(_dotzsh_extract_command_name "$line")" || continue
        [[ -n ${DOTZSH_USED_COMMAND_MAP[$command_name]:-} ]] && continue
        DOTZSH_USED_COMMANDS+=("$command_name")
        DOTZSH_USED_COMMAND_MAP[$command_name]=1
        [ "${#DOTZSH_USED_COMMANDS[@]}" -lt "$DOTZSH_USED_COMMAND_LIMIT" ] || break
    done < <(
        if [ -r "$history_file" ]; then
            tac "$history_file" 2>/dev/null || tail -r "$history_file" 2>/dev/null || cat "$history_file"
        else
            fc -lnr 1 2>/dev/null
        fi
    )

    DOTZSH_USED_COMMANDS_INITIALIZED=1
}

_dotzsh_initialize_all_commands() {
    local command_name=""

    [ "$DOTZSH_ALL_COMMANDS_INITIALIZED" -eq 0 ] || return 0

    DOTZSH_ALL_COMMANDS=()
    DOTZSH_ALL_COMMAND_MAP=()

    for command_name in ${(k)aliases} ${(k)builtins} ${(k)commands} ${(k)functions}; do
        [ -n "$command_name" ] || continue
        [[ "$command_name" == _* ]] && continue
        [[ -n ${DOTZSH_ALL_COMMAND_MAP[$command_name]:-} ]] && continue
        DOTZSH_ALL_COMMANDS+=("$command_name")
        DOTZSH_ALL_COMMAND_MAP[$command_name]=1
    done

    DOTZSH_ALL_COMMANDS_INITIALIZED=1
}

_dotzsh_record_command() {
    local command_name=""

    command_name="$(_dotzsh_extract_command_name "$1")" || return 0
    _dotzsh_remember_command "$command_name"
}

_dotzsh_command_menu() {
    local command_name=""
    local -a other_commands=()
    local -a filtered_used_commands=()
    local -a used_display=()
    local current_prefix="$PREFIX"

    _dotzsh_initialize_used_commands
    _dotzsh_initialize_all_commands

    for command_name in "${DOTZSH_USED_COMMANDS[@]}"; do
        [[ -n ${DOTZSH_ALL_COMMAND_MAP[$command_name]:-} ]] || continue
        [ -z "$current_prefix" ] || [[ "$command_name" == ${~current_prefix}* ]] || continue
        filtered_used_commands+=("$command_name")
        used_display+=("* $command_name")
    done

    for command_name in "${DOTZSH_ALL_COMMANDS[@]}"; do
        [[ -n ${DOTZSH_USED_COMMAND_MAP[$command_name]:-} ]] && continue
        [ -z "$current_prefix" ] || [[ "$command_name" == ${~current_prefix}* ]] || continue
        other_commands+=("$command_name")
    done

    [ "${#filtered_used_commands[@]}" -eq 0 ] || compadd -Q -U -o nosort -d used_display -- "${filtered_used_commands[@]}"
    [ "${#other_commands[@]}" -eq 0 ] || compadd -Q -U -o nosort -- "${other_commands[@]}"

    [ "${#filtered_used_commands[@]}" -gt 0 ] || [ "${#other_commands[@]}" -gt 0 ]
}

compdef _dotzsh_command_menu -command-
add-zsh-hook preexec _dotzsh_record_command

autoload -Uz _gvm _conda _go _node _npm _npx 2>/dev/null
compdef _gvm gvm
compdef _go go gofmt
compdef _conda conda
compdef _node node
compdef _npm npm
compdef _npx npx
