# shellcheck shell=zsh
# Zsh completion for slash commands
# Loaded only when shell is zsh

# Guard: only proceed if zsh completion system is available
(( $+functions[compdef] )) || return 0

___x_cmd_slash___zsh_complete_first_word() {
    # CURRENT == 1: only trigger when completing the first word (command position)
    # PREFIX == /*: and the current input starts with /
    if (( CURRENT == 1 )) && [[ "$PREFIX" == /* ]]; then
        local -a cmds
        local advise_data line name desc

        advise_data="$(___x_cmd slash ls --advise 2>/dev/null)" || advise_data=""

        if [[ -n "$advise_data" ]]; then
            while IFS= read -r line; do
                name="${line%%:*}"
                desc="${line#*:}"
                # Unescape colons in description
                desc="${desc//\\:/:}"
                # Fallback when description is missing or empty
                [[ -n "$desc" ]] || desc="No description"
                # Only add candidates matching the current PREFIX
                [[ -n "$name" && "/$name" == "$PREFIX"* ]] && cmds+=("/$name:$desc")
            done <<< "$advise_data"
        fi

        if (( ${#cmds[@]} > 0 )); then
            _describe -t slash-commands 'slash commands' cmds
        fi
    fi
}

# Bind to first-word completion context, not to the / command itself
compdef ___x_cmd_slash___zsh_complete_first_word -first-
