#/bin/bash

PLUGIN_DIR="/usr/share/eus-avast/plugins"

# Load plugin completions
_em_load_plugin_completions() {
    [ ! -d "${PLUGIN_DIR}" ] && return

    for plugin_path in "${PLUGIN_DIR}"/*; do
        [ ! -d "${plugin_path}" ] && continue

        local completion_file="${plugin_path}/completion.sh"
        if [ -f "${completion_file}" ]; then
            source "${completion_file}"
        fi
    done
}

# Get list of available plugins
_em_get_plugins() {
    local plugins=""
    [ ! -d "${PLUGIN_DIR}" ] && echo "" && return

    for plugin_path in "${PLUGIN_DIR}"/*; do
        [ ! -d "${plugin_path}" ] && continue

        local plugin_name=$(basename "${plugin_path}")
        local conf_file="${plugin_path}/plugin.conf"

        if [ -f "${conf_file}" ]; then
            plugins="${plugins} ${plugin_name}"
        fi
    done

    echo "${plugins}"
}

# Main completion function
_em_completions()
{
    local cur="${COMP_WORDS[COMP_CWORD]}"
    local prev="${COMP_WORDS[COMP_CWORD-1]}"
    local suggestions=""

    # Built-in command completions
    if [ "${COMP_WORDS[1]}" == "boot" ]; then
        suggestions=$(compgen -W "show vars kernel" -- "${cur}")
    elif [ "${COMP_WORDS[1]}" == "compliance" ]; then
        suggestions=$(compgen -W "check report sync report-json" -- "${cur}")
    elif [ "${#COMP_WORDS[@]}" == "2" ]; then
        # First level: show all commands including plugins
        local base_commands="logs help start stop status update vpn compliance version boot"
        local plugin_commands=$(_em_get_plugins)
        suggestions=$(compgen -W "${base_commands} ${plugin_commands}" -- "${cur}")
    else
        # Check if first argument is a plugin command
        local plugin_name="${COMP_WORDS[1]}"
        local completion_func="${plugin_name}_completion"

        if declare -f "${completion_func}" > /dev/null 2>&1; then
            # Call plugin-specific completion function
            suggestions=$(${completion_func})
            suggestions=$(compgen -W "${suggestions}" -- "${cur}")
        fi
    fi

    COMPREPLY=(${suggestions})
}

# Load plugin completions at startup
_em_load_plugin_completions

complete -F _em_completions em
