#!/bin/bash -e

_completion_actl() {
    local current_word="$2"
    local match_word="$2"
    local wrapper_current_word="$2"
    local cword="${COMP_CWORD}"
    local words_string="${COMP_WORDS[*]}"
    local line_prefix="${COMP_LINE:0:COMP_POINT}"
    local -a words=()

    if [[ -n "$line_prefix" ]]; then
        read -r -a words <<< "$line_prefix"
        if [[ "$line_prefix" =~ [[:space:]]$ ]]; then
            wrapper_current_word=""
            cword="${#words[@]}"
        elif [[ ${#words[@]} -gt 0 ]]; then
            wrapper_current_word="${words[${#words[@]}-1]}"
            cword="$(( ${#words[@]} - 1 ))"
        fi
        words_string="${words[*]}"
    fi

    if [[ "$wrapper_current_word" == --*"="* ]]; then
        match_word="${wrapper_current_word#*=}"
    elif [[ "$current_word" != "$wrapper_current_word" && "$current_word" != "" ]]; then
        match_word="$current_word"
    fi

    if [[ "${words[1]}" == sources && "$cword" -eq 3 &&
          ( "${words[2]}" == add || "${words[2]}" == probe-source ) ]]; then
        match_word="$wrapper_current_word"
    fi

    mapfile -t COMPREPLY < <(compgen -W "$(COMP_CWORD="${cword}" COMP_WORDS="${words_string}" /usr/share/alteratorctl/scripts/completion_wrapper "${1}" "${wrapper_current_word}" "${3}")" -- "$match_word")

    if [[ "${words[1]}" == sources && "$cword" -eq 3 &&
          ( "${words[2]}" == add || "${words[2]}" == probe-source ) &&
          "$wrapper_current_word" != -* ]]; then
        # Bash treats ':' as a word break; replace only the UUID suffix in that case.
        if [[ "$wrapper_current_word" == *:* && "$current_word" != "$wrapper_current_word" ]]; then
            local i prefix="${wrapper_current_word%:*}:"
            for i in "${!COMPREPLY[@]}"; do
                COMPREPLY[$i]="${COMPREPLY[$i]#"$prefix"}"
            done
        else
            local -a image_paths=()
            mapfile -t image_paths < <(compgen -f -- "$wrapper_current_word")
            COMPREPLY+=("${image_paths[@]}")
            compopt -o filenames 2>/dev/null || true
        fi
    fi

    compopt +o nospace 2>/dev/null || true
    local candidate
    for candidate in "${COMPREPLY[@]}"; do
        if [[ "$candidate" == *= ]]; then
            compopt -o nospace 2>/dev/null || true
            break
        fi
    done
}

complete -o nosort -F _completion_actl alteratorctl
complete -o nosort -F _completion_actl actl
