# Bash completion script for radp-vf
# Generated by radp-bash-framework

# Helper: Resolve config directory for completion
_radp_vf_comp_config_dir() {
    local config_dir=""
    local i
    for ((i = 1; i < ${#COMP_WORDS[@]}; i++)); do
        case "${COMP_WORDS[i]}" in
            -c|--config)
                config_dir="${COMP_WORDS[i+1]}"
                break
                ;;
            -c=*|--config=*)
                config_dir="${COMP_WORDS[i]#*=}"
                break
                ;;
        esac
    done
    if [[ -z "$config_dir" ]]; then
        config_dir="${RADP_VAGRANT_CONFIG_DIR:-}"
    fi
    if [[ -z "$config_dir" && -f "./vagrant.yaml" ]]; then
        config_dir="."
    fi
    [[ -n "$config_dir" ]] && echo "$config_dir"
}

# Helper: Get env override from command line
_radp_vf_comp_env() {
    local i
    for ((i = 1; i < ${#COMP_WORDS[@]}; i++)); do
        case "${COMP_WORDS[i]}" in
            -e|--env)
                echo "${COMP_WORDS[i+1]}"
                return
                ;;
            -e=*|--env=*)
                echo "${COMP_WORDS[i]#*=}"
                return
                ;;
        esac
    done
    echo "${RADP_VAGRANT_ENV:-}"
}

# Helper: Get cluster value from command line
_radp_vf_comp_cluster() {
    local i
    for ((i = 1; i < ${#COMP_WORDS[@]}; i++)); do
        case "${COMP_WORDS[i]}" in
            -C|--cluster)
                echo "${COMP_WORDS[i+1]}"
                return
                ;;
            -C=*|--cluster=*)
                echo "${COMP_WORDS[i]#*=}"
                return
                ;;
        esac
    done
}

# Helper: Call Ruby completion CLI
_radp_vf_ruby_completion() {
    local config_dir="$1"
    local env_override="$2"
    local type="$3"
    local cluster="${4:-}"
    
    local radp_vf_home="${RADP_VF_HOME:-}"
    local ruby_lib_dir=""
    
    # Auto-detect radp-vf location
    if [[ -z "$radp_vf_home" ]]; then
        local script_path
        script_path="$(command -v radp-vf 2>/dev/null)"
        if [[ -n "$script_path" ]]; then
            # Resolve symlinks: try realpath, readlink -f, or fallback to basic readlink
            local resolved
            resolved="$(realpath "$script_path" 2>/dev/null)" ||
            resolved="$(readlink -f "$script_path" 2>/dev/null)" ||
            resolved="$script_path"
            radp_vf_home="$(cd "$(dirname "$resolved")/.." 2>/dev/null && pwd)"
        fi
    fi
    
    # Detect Ruby lib directory
    if [[ -d "${radp_vf_home}/src/main/ruby/lib/radp_vagrant" ]]; then
        ruby_lib_dir="${radp_vf_home}/src/main/ruby"
    elif [[ -d "${radp_vf_home}/lib/radp_vagrant" ]]; then
        ruby_lib_dir="${radp_vf_home}"
    else
        return 1
    fi
    
    # Expand tilde before processing
    if [[ "$config_dir" == '~'* ]]; then
        config_dir="${config_dir/#\~/$HOME}"
    fi
    # Convert relative config_dir to absolute
    if [[ -n "$config_dir" && "$config_dir" != /* ]]; then
        config_dir="$(cd "$config_dir" 2>/dev/null && pwd)" || return 1
    fi
    
    (cd "$ruby_lib_dir" && ruby -r ./lib/radp_vagrant -e "
        cmd = RadpVagrant::CLI::Completion.new(
            ARGV[0],
            env_override: ARGV[1].empty? ? nil : ARGV[1],
            type: ARGV[2],
            cluster: ARGV[3].empty? ? nil : ARGV[3]
        )
        cmd.execute
    " -- "$config_dir" "$env_override" "$type" "$cluster" 2>/dev/null)
}

_radp_vf() {
    local cur prev words cword

    # Support delegation from other completion functions (e.g., homelabctl vf)
    # When _RADP_VF_DELEGATED is set, skip _init_completion and use pre-set COMP_* variables
    if [[ -z "${_RADP_VF_DELEGATED:-}" ]]; then
        # Direct invocation: use _init_completion if available
        if type _init_completion &>/dev/null; then
            _init_completion || return
        else
            COMPREPLY=()
            cur="${COMP_WORDS[COMP_CWORD]}"
            prev="${COMP_WORDS[COMP_CWORD-1]}"
            words=("${COMP_WORDS[@]}")
            cword="$COMP_CWORD"
        fi
    else
        # Delegated invocation: use pre-set COMP_* variables
        COMPREPLY=()
        cur="${COMP_WORDS[COMP_CWORD]}"
        prev="${COMP_WORDS[COMP_CWORD-1]}"
        words=("${COMP_WORDS[@]}")
        cword="$COMP_CWORD"
    fi

    local i cmd_path=""

    # Known command paths (generated)
    local _all_cmds=" completion dump-config generate info init list template template_list template_show upgrade validate version vg  "

    # Build cmd_path: skip global option values, validate against known commands
    for ((i = 1; i < cword; i++)); do
        case "${words[i]}" in
            -c|--config|-e|--env)
                ((i++)) ;;
            -*) ;;
            *)
                local _test_path
                if [[ -z "$cmd_path" ]]; then
                    _test_path="${words[i]}"
                else
                    _test_path="$cmd_path ${words[i]}"
                fi
                if [[ " $_all_cmds " == *" ${_test_path// /_} "* ]]; then
                    cmd_path="$_test_path"
                fi
                ;;
        esac
    done

    # Command completions
    case "$cmd_path" in
        '')
            COMPREPLY=($(compgen -W "completion dump-config generate info init list template upgrade validate version vg  -q --quiet -v --verbose --debug --show-config --all --json -c --config -e --env --help --version" -- "$cur"))
            ;;
        'completion')
            # 计算参数位置（减去命令路径深度）
            local arg_idx=0
            for ((i = 1; i < cword; i++)); do
                case "${words[i]}" in
                    -c|--config|-e|--env)
                        ((i++)) ;;
                    -*) ;;
                    *) ((arg_idx++)) ;;
                esac
            done
            ((arg_idx -= 1)) || true
            # 根据参数位置补全
            case "$arg_idx" in
                0)
                    COMPREPLY=($(compgen -W "bash zsh" -- "$cur"))
                    return
                    ;;
            esac
            COMPREPLY=($(compgen -W "--help -c --config -e --env" -- "$cur"))
            ;;
        'dump-config')
            COMPREPLY=($(compgen -W "--help -c --config -e --env -f --format -o --output" -- "$cur"))
            ;;
        'generate')
            COMPREPLY=($(compgen -W "--help -c --config -e --env" -- "$cur"))
            ;;
        'info')
            COMPREPLY=($(compgen -W "--help -c --config -e --env" -- "$cur"))
            ;;
        'init')
            COMPREPLY=($(compgen -W "--help -c --config -e --env -t --template --set --force --dry-run" -- "$cur"))
            ;;
        'list')
            COMPREPLY=($(compgen -W "--help -c --config -e --env -a --all -p --provisions -s --synced-folders -t --triggers -S --status" -- "$cur"))
            ;;
        'template')
            COMPREPLY=($(compgen -W "list show  --help" -- "$cur"))
            ;;
        'template list')
            COMPREPLY=($(compgen -W "--help -c --config -e --env" -- "$cur"))
            ;;
        'template show')
            COMPREPLY=($(compgen -W "--help -c --config -e --env" -- "$cur"))
            ;;
        'upgrade')
            COMPREPLY=($(compgen -W "--help -c --config -e --env --check --force -y --yes --version" -- "$cur"))
            ;;
        'validate')
            COMPREPLY=($(compgen -W "--help -c --config -e --env" -- "$cur"))
            ;;
        'version')
            COMPREPLY=($(compgen -W "--help -c --config -e --env" -- "$cur"))
            ;;
        'vg'*)
            # Dynamic completion for vg command
            local config_dir env_override cluster_val
            config_dir="$(_radp_vf_comp_config_dir)"
            env_override="$(_radp_vf_comp_env)"
            
            # Check if completing option value (space-separated form: -C xxx)
            case "$prev" in
                -C|--cluster)
                    if [[ -n "$config_dir" ]]; then
                        local clusters
                        clusters="$(_radp_vf_ruby_completion "$config_dir" "$env_override" "clusters")"
                        COMPREPLY=($(compgen -W "$clusters" -- "$cur"))
                    fi
                    return
                    ;;
                -G|--guest-ids)
                    cluster_val="$(_radp_vf_comp_cluster)"
                    if [[ -n "$config_dir" && -n "$cluster_val" ]]; then
                        cluster_val="${cluster_val%%,*}"
                        local guest_ids
                        guest_ids="$(_radp_vf_ruby_completion "$config_dir" "$env_override" "guests" "$cluster_val")"
                        COMPREPLY=($(compgen -W "$guest_ids" -- "$cur"))
                    fi
                    return
                    ;;
                --provision-with)
                    if [[ -n "$config_dir" ]]; then
                        local provisions
                        provisions="$(_radp_vf_ruby_completion "$config_dir" "$env_override" "provisions")"
                        COMPREPLY=($(compgen -W "$provisions" -- "$cur"))
                        type __ltrim_colon_completions &>/dev/null && __ltrim_colon_completions "$cur"
                    fi
                    return
                    ;;
                -c|--config|-e|--env)
                    return
                    ;;
            esac
            
            # Check if completing option value (equals form: --cluster=xxx)
            case "$cur" in
                -C=*|--cluster=*)
                    if [[ -n "$config_dir" ]]; then
                        local prefix="${cur%%=*}="
                        local typed="${cur#*=}"
                        local clusters
                        clusters="$(_radp_vf_ruby_completion "$config_dir" "$env_override" "clusters")"
                        COMPREPLY=($(compgen -P "$prefix" -W "$clusters" -- "$typed"))
                    fi
                    return
                    ;;
                -G=*|--guest-ids=*)
                    cluster_val="$(_radp_vf_comp_cluster)"
                    if [[ -n "$config_dir" && -n "$cluster_val" ]]; then
                        local prefix="${cur%%=*}="
                        local typed="${cur#*=}"
                        cluster_val="${cluster_val%%,*}"
                        local guest_ids
                        guest_ids="$(_radp_vf_ruby_completion "$config_dir" "$env_override" "guests" "$cluster_val")"
                        COMPREPLY=($(compgen -P "$prefix" -W "$guest_ids" -- "$typed"))
                    fi
                    return
                    ;;
                --provision-with=*)
                    if [[ -n "$config_dir" ]]; then
                        local prefix="${cur%%=*}="
                        local typed="${cur#*=}"
                        local provisions
                        provisions="$(_radp_vf_ruby_completion "$config_dir" "$env_override" "provisions")"
                        COMPREPLY=($(compgen -P "$prefix" -W "$provisions" -- "$typed"))
                        type __ltrim_colon_completions &>/dev/null && __ltrim_colon_completions "$typed"
                    fi
                    return
                    ;;
            esac
            
            # Detect vagrant subcommand position: find the first non-option word after vg
            local vg_pos=-1 vagrant_subcmd=""
            for ((i = 1; i < ${#words[@]}; i++)); do
                case "${words[i]}" in
                    -c|--config|-e|--env|-C|--cluster|-G|--guest-ids)
                        ((i++)) ;;
                    -*) ;;
                    vg)
                        vg_pos=$i ;;
                    *)
                        if [[ $vg_pos -ge 0 && -z "$vagrant_subcmd" ]]; then
                            vagrant_subcmd="${words[i]}"
                        fi
                        ;;
                esac
            done
            
            # If a vagrant subcommand was detected, try delegating to vagrant completion
            if [[ -n "$vagrant_subcmd" ]]; then
                if type _vagrant &>/dev/null; then
                    # Build vagrant words: skip framework options, keep vagrant args
                    local -a vagrant_words=("vagrant")
                    local skip_next=false
                    for ((i = vg_pos + 1; i < ${#words[@]}; i++)); do
                        if $skip_next; then skip_next=false; continue; fi
                        case "${words[i]}" in
                            -c|--config|-e|--env|-C|--cluster|-G|--guest-ids) skip_next=true ;;
                            *) vagrant_words+=("${words[i]}") ;;
                        esac
                    done
                    # Save/restore COMP_* around delegation
                    local saved_comp_words=("${COMP_WORDS[@]}")
                    local saved_comp_cword=$COMP_CWORD
                    local saved_comp_line="$COMP_LINE"
                    local saved_comp_point=$COMP_POINT
                    COMP_WORDS=("${vagrant_words[@]}")
                    COMP_CWORD=$(( ${#vagrant_words[@]} - 1 ))
                    COMP_LINE="${vagrant_words[*]}"
                    COMP_POINT=${#COMP_LINE}
                    _vagrant 2>/dev/null
                    # Restore COMP_*
                    COMP_WORDS=("${saved_comp_words[@]}")
                    COMP_CWORD=$saved_comp_cword
                    COMP_LINE="$saved_comp_line"
                    COMP_POINT=$saved_comp_point
                    # Augment with framework options if completing an option
                    if [[ "$cur" == -* ]]; then
                        COMPREPLY+=($(compgen -W "-c --config -e --env -C --cluster -G --guest-ids" -- "$cur"))
                    elif [[ -n "$config_dir" ]]; then
                        # Also add machine names
                        local machines
                        machines="$(_radp_vf_ruby_completion "$config_dir" "$env_override" "machines")"
                        if [[ -n "$machines" ]]; then
                            COMPREPLY+=($(compgen -W "$machines" -- "$cur"))
                        fi
                    fi
                    return
                fi
                # Fallback: no _vagrant available, offer framework options + machines
                if [[ "$cur" == -* ]]; then
                    COMPREPLY=($(compgen -W "--help -c --config -e --env -C --cluster -G --guest-ids" -- "$cur"))
                elif [[ -n "$config_dir" ]]; then
                    local machines
                    machines="$(_radp_vf_ruby_completion "$config_dir" "$env_override" "machines")"
                    COMPREPLY=($(compgen -W "$machines" -- "$cur"))
                fi
                return
            fi
            
            # No vagrant subcommand yet: complete vg-level options + vagrant commands + machines
            if [[ "$cur" == -* ]]; then
                COMPREPLY=($(compgen -W "--help -c --config -e --env -C --cluster -G --guest-ids" -- "$cur"))
            else
                local vagrant_cmds="box cloud connect destroy global-status halt help init login package plugin port powershell provision push rdp reload resume rsync rsync-auto serve snapshot ssh ssh-config status suspend up upload validate version winrm winrm-config"
                if [[ -n "$config_dir" ]]; then
                    local machines
                    machines="$(_radp_vf_ruby_completion "$config_dir" "$env_override" "machines")"
                    COMPREPLY=($(compgen -W "$vagrant_cmds $machines" -- "$cur"))
                else
                    COMPREPLY=($(compgen -W "$vagrant_cmds" -- "$cur"))
                fi
            fi
            ;;
        *)
            COMPREPLY=()
            ;;
    esac
}

complete -F _radp_vf radp-vf
