# Bash completion for the native ompi wrapper.

_ompi_omp_completion()
{
    # Reuse the installed OMP catalog, including its dynamic value completions.
    if ! declare -F _omp >/dev/null; then
        command -v omp >/dev/null 2>&1 || return 0
        local omp_registration
        omp_registration=$(complete -p omp 2>/dev/null) || omp_registration=""
        # shellcheck source=/dev/null
        source <(command omp completions bash 2>/dev/null)
        # The delegated catalog registers omp too; only ompi belongs to us.
        if [[ -n $omp_registration ]]; then
            eval "$omp_registration"
        else
            complete -r omp 2>/dev/null || :
        fi
    fi

    if declare -F _omp >/dev/null; then
        _omp "$@"
    fi
}

_ompi_control_completion()
{
    # Candidate lookups are not operator feature invocations.
    local -x OMPI_USAGE=0
    # _comp_initialize populates prev through Bash dynamic scope; keep it local.
    # shellcheck disable=SC2034
    local cur prev words cword
    _comp_initialize -n '=:' || return
    COMPREPLY=()
    if (( cword == 2 )); then
        mapfile -t COMPREPLY < <(compgen -W 'list restart resume send steer restore recover cleanup usage help version' -- "$cur")
        return 0
    fi
    local action=${words[2]}
    if [[ $action == help ]]; then
        if (( cword == 3 )); then
            mapfile -t COMPREPLY < <(compgen -W 'list restart resume send steer restore recover cleanup usage version' -- "$cur")
        fi
        return 0
    fi
    if [[ $action == usage ]]; then
        (( cword == 3 )) && mapfile -t COMPREPLY < <(compgen -W '--json' -- "$cur")
        return 0
    fi
    if [[ $action == recover ]]; then
        (( cword == 3 )) && _comp_compgen_filedir
        return 0
    fi
    if [[ $action == send || $action == steer ]]; then
        local index token option id state _remainder
        local -a profile_args=() candidates=()
        local -A consumed=()
        for (( index=3; index<cword; index++ )); do
            token=${words[index]}
            case $token in
                --profile)
                    (( index+1 < cword )) || return 0
                    (( index++ ))
                    profile_args=(--profile "${words[index]}")
                    consumed[--profile]=1
                    ;;
                --profile=*)
                    profile_args=("$token")
                    consumed[--profile]=1
                    ;;
                --json) consumed[$token]=1 ;;
                *) return 0 ;;
            esac
        done
        [[ $cur == --profile=* ]] && return 0
        if [[ $cur == -* ]]; then
            for option in --profile --json; do
                [[ -n ${consumed[$option]} ]] || candidates+=("$option")
            done
        else
            while read -r id state _remainder; do
                [[ $id =~ ^[a-f0-9]{12,32}$ && $state == running ]] && candidates+=("$id")
            done < <(command ompi control list "${profile_args[@]}" 2>/dev/null)
        fi
        mapfile -t COMPREPLY < <(compgen -W "${candidates[*]}" -- "$cur")
        return 0
    fi
    [[ $action == list || $action == restart || $action == resume || $action == cleanup || $action == restore ]] || return 0

    local index token name next pending='' selector='' selector_prefix=''
    local -A used=()
    local -a positionals=() profile_arguments=()
    for (( index=3; index<cword; index++ )); do
        token=${words[index]}
        [[ $token == -- ]] && return 0
        if [[ $token != -* ]]; then
            positionals+=("$token")
            continue
        fi
        name=${token%%=*}
        [[ $name == -h ]] && name=--help
        used[$name]=1
        case $name in
            --help|--version) return 0 ;;
            --profile|--instance|--from|--query)
                if [[ $token == *=* ]]; then
                    [[ $name == --profile ]] && profile_arguments=(--profile "${token#*=}")
                    continue
                fi
                if (( index+1 >= cword )); then
                    pending=$name
                    break
                fi
                next=${words[index+1]}
                if [[ $next == = ]]; then
                    (( index++ ))
                    if (( index+1 >= cword )); then
                        pending=$name
                        break
                    fi
                    next=${words[index+1]}
                fi
                [[ $next == -* ]] && return 0
                [[ $name == --profile ]] && profile_arguments=(--profile "$next")
                (( index++ ))
                ;;
        esac
    done

    local options='--profile --json' operation=${positionals[0]} needs_argument=false
    [[ $action == list ]] && options+=' --query'
    if [[ $action == restart ]]; then
        options+=' --no-wait'
        (( ${#positionals[@]} > 1 )) && return 0
    elif [[ $action == resume ]]; then
        options='--profile'
        (( ${#positionals[@]} > 1 )) && return 0
    elif [[ $action == restore ]]; then
        options='--profile'
        case $operation in
            list) options='--json --from --profile' ;;
            history) options='--json --profile' ;;
            export) options='--from --profile' ;;
            save) options='--instance --profile'; needs_argument=true ;;
            name|slot|from) needs_argument=true ;;
        esac
        local maximum=1
        [[ $needs_argument == true ]] && maximum=2
        (( ${#positionals[@]} > maximum )) && return 0
    elif (( ${#positionals[@]} > 0 )); then
        return 0
    fi
    for name in "${!used[@]}"; do
        [[ " $options " == *" $name "* ]] || return 0
    done
    case $pending in
        --profile|--instance) return 0 ;;
        --from) selector=from ;;
    esac
    case $cur in
        --profile=*|--instance=*|--query=*) return 0 ;;
        --from=*) selector=from; selector_prefix='--from=' ;;
    esac
    if [[ $action == restore && $needs_argument == true && ${#positionals[@]} == 1 ]]; then
        case $operation in
            slot|from) selector=$operation ;;
            save) return 0 ;;
            name) ;;
        esac
    fi
    if [[ -n $selector ]]; then
        [[ $action == restore ]] || return 0
        if [[ -n $selector_prefix || $pending == --from ]]; then
            [[ $operation == list || $operation == export ]] || return 0
        fi
        local position _saved_name identity _remainder
        local -a identities=()
        if [[ $selector == from ]]; then
            while read -r position identity _remainder; do
                [[ $position =~ ^[0-9]+\)$ && $identity =~ ^[a-f0-9]{32}$ ]] || continue
                identities+=("$selector_prefix$identity")
            done < <(command ompi control restore history "${profile_arguments[@]}" 2>/dev/null)
        else
            while read -r position _saved_name identity _remainder; do
                [[ $position =~ ^[0-9]+\)$ && $identity =~ ^[a-f0-9]{32}$ ]] || continue
                identities+=("$identity")
            done < <(command ompi control restore list "${profile_arguments[@]}" 2>/dev/null)
        fi
        mapfile -t COMPREPLY < <(compgen -W "${identities[*]}" -- "$cur")
        return 0
    fi
    [[ -n $pending ]] && return 0
    if [[ $cur != -* ]]; then
        if [[ $action == restart && ${#positionals[@]} == 0 ]]; then
            mapfile -t COMPREPLY < <(compgen -W 'all' -- "$cur")
        elif [[ $action == restore && ( ${#positionals[@]} == 0 || ( $operation == name && ${#positionals[@]} == 1 ) ) ]]; then
            local position saved_name _remainder
            local verbs='list history checkpoint export slot from save name'
            local -a names=()
            [[ -z $operation ]] && read -r -a names <<< "$verbs"
            while read -r position saved_name _remainder; do
                [[ $position =~ ^[0-9]+\)$ && $saved_name =~ ^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$ ]] || continue
                [[ -z $operation && ( $saved_name == import-legacy || " $verbs " == *" $saved_name "* ) ]] && continue
                names+=("$saved_name")
            done < <(command ompi control restore list "${profile_arguments[@]}" 2>/dev/null)
            mapfile -t COMPREPLY < <(compgen -W "${names[*]}" -- "$cur")
        fi
        return 0
    fi
    [[ $needs_argument == true && ${#positionals[@]} == 1 ]] && return 0
    local option
    local -a available=()
    for option in $options; do
        [[ -n ${used[$option]} ]] || available+=("$option")
    done
    mapfile -t COMPREPLY < <(compgen -W "${available[*]}" -- "$cur")
    return 0
}

_ompi()
{
    # _comp_initialize populates prev through Bash dynamic scope; keep it local.
    # shellcheck disable=SC2034
    local cur prev words cword
    _comp_initialize -n = || return
    if (( cword == 1 )); then
        _ompi_omp_completion "$@"
        [[ control == "$cur"* ]] && COMPREPLY+=(control)
        return 0
    fi
    if [[ ${words[1]} == control ]]; then
        _ompi_control_completion "$@"
    else
        _ompi_omp_completion "$@"
    fi
}

complete -F _ompi ompi
