# homelabctl completion helper functions

_homelabctl_complete_packages() {
  homelabctl -q setup list --names-only 2>/dev/null
}

_homelabctl_complete_categories() {
  homelabctl -q setup list --category-names 2>/dev/null
}

_homelabctl_complete_profiles() {
  homelabctl -q setup profile list --names-only 2>/dev/null
}

# Get vf config_dir from homelabctl config (for completion delegation)
_homelabctl_vf_config_dir() {
  # Priority 1: Check if already set via env var
  if [[ -n "${RADP_VAGRANT_CONFIG_DIR:-}" ]]; then
    echo "$RADP_VAGRANT_CONFIG_DIR"
    return
  fi
  # Priority 2: Default homelabctl vf config location
  local default_dir="$HOME/.config/homelabctl/vagrant"
  if [[ -f "$default_dir/vagrant.yaml" ]]; then
    echo "$default_dir"
    return
  fi
  # Priority 3: Current directory if it has vagrant.yaml
  if [[ -f "./vagrant.yaml" ]]; then
    echo "."
    return
  fi
}

# Get vf env from homelabctl config
_homelabctl_vf_env() {
  # Check if set via env var
  if [[ -n "${RADP_VAGRANT_ENV:-}" ]]; then
    echo "$RADP_VAGRANT_ENV"
    return
  fi
  # Try to read from homelabctl's config.yaml
  local config_file="$HOME/.config/homelabctl/config.yaml"
  if [[ -f "$config_file" ]] && command -v yq &>/dev/null; then
    local env_val
    env_val=$(yq -r '.radp.env // empty' "$config_file" 2>/dev/null)
    [[ -n "$env_val" ]] && echo "$env_val"
  fi
}

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

_homelabctl() {
    local cur prev words cword

    # 兼容模式：如果 _init_completion 不存在，使用手动初始化
    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

    local i cmd_path=""

    # Known command paths (generated)
    local _all_cmds=" completion gitlab gitlab_backup gitlab_backup_cleanup gitlab_backup_create gitlab_backup_list gitlab_healthcheck gitlab_init gitlab_install gitlab_reset-password gitlab_restart gitlab_restore gitlab_runner gitlab_runner_install gitlab_start gitlab_status gitlab_stop init init_all init_k8s init_setup init_vf k8s k8s_addon k8s_addon_install k8s_addon_list k8s_addon_profile k8s_addon_profile_apply k8s_addon_profile_list k8s_addon_profile_show k8s_addon_quickstart k8s_addon_uninstall k8s_backup k8s_backup_cleanup k8s_backup_create k8s_backup_list k8s_backup_restore k8s_health k8s_init k8s_init_master k8s_init_worker k8s_install k8s_token k8s_token_create k8s_token_get k8s_upgrade k8s_upgrade_apply k8s_upgrade_cluster k8s_upgrade_node k8s_upgrade_plan setup setup_configure setup_configure_chrony setup_configure_docker setup_configure_docker_acceleration setup_configure_docker_rootless setup_configure_expand-lvm setup_configure_gpg-import setup_configure_gpg-preset setup_configure_list setup_configure_yadm setup_deps setup_info setup_install setup_list setup_profile setup_profile_apply setup_profile_list setup_profile_show setup_uninstall upgrade version vf  "

    # Build cmd_path: skip global option values, validate against known commands
    for ((i = 1; i < cword; i++)); do
        case "${words[i]}" in
            -*) ;;
            *)
                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 gitlab init k8s setup upgrade version vf  -q --quiet -v --verbose --debug --show-config --all --json  --help --version" -- "$cur"))
            ;;
        'completion')
            # 计算参数位置（减去命令路径深度）
            local arg_idx=0
            for ((i = 1; i < cword; i++)); do
                case "${words[i]}" in
                    -*) ;;
                    *) ((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 " -- "$cur"))
            ;;
        'gitlab')
            COMPREPLY=($(compgen -W "backup healthcheck init install reset-password restart restore runner start status stop  --help" -- "$cur"))
            ;;
        'gitlab backup')
            COMPREPLY=($(compgen -W "cleanup create list  --help" -- "$cur"))
            ;;
        'gitlab backup cleanup')
            COMPREPLY=($(compgen -W "--help  --keep-days --dry-run" -- "$cur"))
            ;;
        'gitlab backup create')
            COMPREPLY=($(compgen -W "--help  --target --type --skip-remote --dry-run" -- "$cur"))
            ;;
        'gitlab backup list')
            COMPREPLY=($(compgen -W "--help  --type" -- "$cur"))
            ;;
        'gitlab healthcheck')
            COMPREPLY=($(compgen -W "--help  --verbose --check-secrets --dry-run" -- "$cur"))
            ;;
        'gitlab init')
            COMPREPLY=($(compgen -W "--help  --user-config --backup-schedule --skip-crontab --skip-reconfigure --dry-run" -- "$cur"))
            ;;
        'gitlab install')
            COMPREPLY=($(compgen -W "--help  -t --type -v --version --data-dir --skip-postfix --dry-run" -- "$cur"))
            ;;
        'gitlab reset-password')
            COMPREPLY=($(compgen -W "--help  --force --dry-run" -- "$cur"))
            ;;
        'gitlab restart')
            COMPREPLY=($(compgen -W "--help  --service --dry-run" -- "$cur"))
            ;;
        'gitlab restore')
            COMPREPLY=($(compgen -W "--help  --type --source --force --dry-run" -- "$cur"))
            ;;
        'gitlab runner')
            COMPREPLY=($(compgen -W "install  --help" -- "$cur"))
            ;;
        'gitlab runner install')
            COMPREPLY=($(compgen -W "--help  -v --version --dry-run" -- "$cur"))
            ;;
        'gitlab start')
            COMPREPLY=($(compgen -W "--help  --service --dry-run" -- "$cur"))
            ;;
        'gitlab status')
            COMPREPLY=($(compgen -W "--help  --services" -- "$cur"))
            ;;
        'gitlab stop')
            COMPREPLY=($(compgen -W "--help  --service --dry-run" -- "$cur"))
            ;;
        'init')
            COMPREPLY=($(compgen -W "all k8s setup vf  --help" -- "$cur"))
            ;;
        'init all')
            COMPREPLY=($(compgen -W "--help  --force --dry-run" -- "$cur"))
            ;;
        'init k8s')
            COMPREPLY=($(compgen -W "--help  --force --dry-run" -- "$cur"))
            ;;
        'init setup')
            COMPREPLY=($(compgen -W "--help  --force --dry-run" -- "$cur"))
            ;;
        'init vf')
            COMPREPLY=($(compgen -W "--help " -- "$cur"))
            ;;
        'k8s')
            COMPREPLY=($(compgen -W "addon backup health init install token upgrade  --help" -- "$cur"))
            ;;
        'k8s addon')
            COMPREPLY=($(compgen -W "install list profile quickstart uninstall  --help" -- "$cur"))
            ;;
        'k8s addon install')
            COMPREPLY=($(compgen -W "--help  -v --version -f --values --dry-run" -- "$cur"))
            ;;
        'k8s addon list')
            COMPREPLY=($(compgen -W "--help  --installed" -- "$cur"))
            ;;
        'k8s addon profile')
            COMPREPLY=($(compgen -W "apply list show  --help" -- "$cur"))
            ;;
        'k8s addon profile apply')
            COMPREPLY=($(compgen -W "--help  --dry-run --continue --skip-installed" -- "$cur"))
            ;;
        'k8s addon profile list')
            COMPREPLY=($(compgen -W "--help  --names-only" -- "$cur"))
            ;;
        'k8s addon profile show')
            COMPREPLY=($(compgen -W "--help " -- "$cur"))
            ;;
        'k8s addon quickstart')
            COMPREPLY=($(compgen -W "--help  --dry-run --continue --skip-installed" -- "$cur"))
            ;;
        'k8s addon uninstall')
            COMPREPLY=($(compgen -W "--help  --dry-run" -- "$cur"))
            ;;
        'k8s backup')
            COMPREPLY=($(compgen -W "cleanup create list restore  --help" -- "$cur"))
            ;;
        'k8s backup cleanup')
            COMPREPLY=($(compgen -W "--help  --keep-days -d --dir --dry-run" -- "$cur"))
            ;;
        'k8s backup create')
            COMPREPLY=($(compgen -W "--help  -d --dir --dry-run" -- "$cur"))
            ;;
        'k8s backup list')
            COMPREPLY=($(compgen -W "--help  -d --dir" -- "$cur"))
            ;;
        'k8s backup restore')
            COMPREPLY=($(compgen -W "--help  --data-dir --dry-run --force" -- "$cur"))
            ;;
        'k8s health')
            COMPREPLY=($(compgen -W "--help  --verbose" -- "$cur"))
            ;;
        'k8s init')
            COMPREPLY=($(compgen -W "master worker  --help" -- "$cur"))
            ;;
        'k8s init master')
            COMPREPLY=($(compgen -W "--help  -a --apiserver-advertise-address -p --pod-network-cidr -e --control-plane-endpoint --dry-run" -- "$cur"))
            ;;
        'k8s init worker')
            COMPREPLY=($(compgen -W "--help  -c --control-plane -t --token --discovery-token-ca-cert-hash -u --ssh-user -i --ssh-key --dry-run" -- "$cur"))
            ;;
        'k8s install')
            COMPREPLY=($(compgen -W "--help  -t --type -v --version --skip-prerequisites --skip-container-runtime --dry-run" -- "$cur"))
            ;;
        'k8s token')
            COMPREPLY=($(compgen -W "create get  --help" -- "$cur"))
            ;;
        'k8s token create')
            COMPREPLY=($(compgen -W "--help  --print-join-command" -- "$cur"))
            ;;
        'k8s token get')
            COMPREPLY=($(compgen -W "--help  --create --join-command" -- "$cur"))
            ;;
        'k8s upgrade')
            COMPREPLY=($(compgen -W "apply cluster node plan  --help" -- "$cur"))
            ;;
        'k8s upgrade apply')
            COMPREPLY=($(compgen -W "--help  --ignore-preflight-errors -y --yes --dry-run" -- "$cur"))
            ;;
        'k8s upgrade cluster')
            COMPREPLY=($(compgen -W "--help  --ignore-preflight-errors -u --ssh-user -i --ssh-key -y --yes --dry-run" -- "$cur"))
            ;;
        'k8s upgrade node')
            COMPREPLY=($(compgen -W "--help  -v --version -r --role --ignore-preflight-errors --skip-drain -y --yes --dry-run" -- "$cur"))
            ;;
        'k8s upgrade plan')
            COMPREPLY=($(compgen -W "--help  --ignore-preflight-errors" -- "$cur"))
            ;;
        'setup')
            COMPREPLY=($(compgen -W "configure deps info install list profile uninstall  --help" -- "$cur"))
            ;;
        'setup configure')
            COMPREPLY=($(compgen -W "chrony docker expand-lvm gpg-import gpg-preset list yadm  --help" -- "$cur"))
            ;;
        'setup configure chrony')
            COMPREPLY=($(compgen -W "--help  --servers --pool --timezone --sync-now --dry-run" -- "$cur"))
            ;;
        'setup configure docker')
            COMPREPLY=($(compgen -W "acceleration rootless  --help" -- "$cur"))
            ;;
        'setup configure docker acceleration')
            COMPREPLY=($(compgen -W "--help  --proxy --https-proxy --no-proxy --mirrors --remove-proxy --dry-run" -- "$cur"))
            ;;
        'setup configure docker rootless')
            COMPREPLY=($(compgen -W "--help  -u --user --dry-run" -- "$cur"))
            ;;
        'setup configure expand-lvm')
            COMPREPLY=($(compgen -W "--help  --partition --vg --lv --dry-run" -- "$cur"))
            ;;
        'setup configure gpg-import')
            COMPREPLY=($(compgen -W "--help  --public-key --public-key-file --secret-key-file --passphrase --passphrase-file --key-id --keyserver --trust-level --ownertrust-file --user --dry-run" -- "$cur"))
            ;;
        'setup configure gpg-preset')
            COMPREPLY=($(compgen -W "--help  --key-uid --passphrase --passphrase-file --user --no-auto-config --dry-run" -- "$cur"))
            ;;
        'setup configure list')
            COMPREPLY=($(compgen -W "--help " -- "$cur"))
            ;;
        'setup configure yadm')
            COMPREPLY=($(compgen -W "--help  --repo-url --class --https-user --https-token --https-token-file --ssh-key-file --ssh-host --ssh-port --user --bootstrap --decrypt --strict-host-key --dry-run" -- "$cur"))
            ;;
        'setup deps')
            # 计算参数位置（减去命令路径深度）
            local arg_idx=0
            for ((i = 1; i < cword; i++)); do
                case "${words[i]}" in
                    -*) ;;
                    *) ((arg_idx++)) ;;
                esac
            done
            ((arg_idx -= 2)) || true
            # 根据参数位置补全
            case "$arg_idx" in
                0)
                    local completions
                    completions=$(_homelabctl_complete_packages 2>/dev/null)
                    COMPREPLY=($(compgen -W "$completions" -- "$cur"))
                    return
                    ;;
            esac
            COMPREPLY=($(compgen -W "--help  --reverse" -- "$cur"))
            ;;
        'setup info')
            # 计算参数位置（减去命令路径深度）
            local arg_idx=0
            for ((i = 1; i < cword; i++)); do
                case "${words[i]}" in
                    -*) ;;
                    *) ((arg_idx++)) ;;
                esac
            done
            ((arg_idx -= 2)) || true
            # 根据参数位置补全
            case "$arg_idx" in
                0)
                    local completions
                    completions=$(_homelabctl_complete_packages 2>/dev/null)
                    COMPREPLY=($(compgen -W "$completions" -- "$cur"))
                    return
                    ;;
            esac
            COMPREPLY=($(compgen -W "--help  --all-platforms" -- "$cur"))
            ;;
        'setup install')
            # 计算参数位置（减去命令路径深度）
            local arg_idx=0
            for ((i = 1; i < cword; i++)); do
                case "${words[i]}" in
                    -v|--version)
                        ((i++)) ;;
                    -*) ;;
                    *) ((arg_idx++)) ;;
                esac
            done
            ((arg_idx -= 2)) || true
            # 根据参数位置补全
            case "$arg_idx" in
                0)
                    local completions
                    completions=$(_homelabctl_complete_packages 2>/dev/null)
                    COMPREPLY=($(compgen -W "$completions" -- "$cur"))
                    return
                    ;;
            esac
            COMPREPLY=($(compgen -W "--help  -v --version --dry-run --no-deps" -- "$cur"))
            ;;
        'setup list')
            case "$prev" in
                -c)
                    local completions
                    completions=$(_homelabctl_complete_categories 2>/dev/null)
                    COMPREPLY=($(compgen -W "$completions" -- "$cur"))
                    return
                    ;;
                --category)
                    local completions
                    completions=$(_homelabctl_complete_categories 2>/dev/null)
                    COMPREPLY=($(compgen -W "$completions" -- "$cur"))
                    return
                    ;;
            esac
            COMPREPLY=($(compgen -W "--help  -c --category --installed --categories --names-only --category-names" -- "$cur"))
            ;;
        'setup profile')
            COMPREPLY=($(compgen -W "apply list show  --help" -- "$cur"))
            ;;
        'setup profile apply')
            # 计算参数位置（减去命令路径深度）
            local arg_idx=0
            for ((i = 1; i < cword; i++)); do
                case "${words[i]}" in
                    -*) ;;
                    *) ((arg_idx++)) ;;
                esac
            done
            ((arg_idx -= 3)) || true
            # 根据参数位置补全
            case "$arg_idx" in
                0)
                    local completions
                    completions=$(_homelabctl_complete_profiles 2>/dev/null)
                    COMPREPLY=($(compgen -W "$completions" -- "$cur"))
                    return
                    ;;
            esac
            COMPREPLY=($(compgen -W "--help  --dry-run --continue --skip-installed --no-deps" -- "$cur"))
            ;;
        'setup profile list')
            COMPREPLY=($(compgen -W "--help  --names-only" -- "$cur"))
            ;;
        'setup profile show')
            # 计算参数位置（减去命令路径深度）
            local arg_idx=0
            for ((i = 1; i < cword; i++)); do
                case "${words[i]}" in
                    -*) ;;
                    *) ((arg_idx++)) ;;
                esac
            done
            ((arg_idx -= 3)) || true
            # 根据参数位置补全
            case "$arg_idx" in
                0)
                    local completions
                    completions=$(_homelabctl_complete_profiles 2>/dev/null)
                    COMPREPLY=($(compgen -W "$completions" -- "$cur"))
                    return
                    ;;
            esac
            COMPREPLY=($(compgen -W "--help " -- "$cur"))
            ;;
        'setup uninstall')
            # 计算参数位置（减去命令路径深度）
            local arg_idx=0
            for ((i = 1; i < cword; i++)); do
                case "${words[i]}" in
                    -*) ;;
                    *) ((arg_idx++)) ;;
                esac
            done
            ((arg_idx -= 2)) || true
            # 根据参数位置补全
            case "$arg_idx" in
                0)
                    local completions
                    completions=$(_homelabctl_complete_packages 2>/dev/null)
                    COMPREPLY=($(compgen -W "$completions" -- "$cur"))
                    return
                    ;;
            esac
            COMPREPLY=($(compgen -W "--help  --purge --dry-run" -- "$cur"))
            ;;
        'upgrade')
            COMPREPLY=($(compgen -W "--help  --check --force -y --yes --version" -- "$cur"))
            ;;
        'version')
            COMPREPLY=($(compgen -W "--help " -- "$cur"))
            ;;
        'vf')
            # Delegate to radp-vf completion
            if type _radp_vf &>/dev/null; then
                # Set config from homelabctl config if not in command line
                local _hctl_vf_config_dir
                _hctl_vf_config_dir="$(_homelabctl_vf_config_dir)"
                [[ -n "$_hctl_vf_config_dir" ]] && export RADP_VAGRANT_CONFIG_DIR="$_hctl_vf_config_dir"
                local _hctl_vf_env
                _hctl_vf_env="$(_homelabctl_vf_env)"
                [[ -n "$_hctl_vf_env" ]] && export RADP_VAGRANT_ENV="$_hctl_vf_env"
                local radp_vf_words=("radp-vf" "${words[@]:2}")
                local radp_vf_cword=$((cword - 1))
                COMP_WORDS=("${radp_vf_words[@]}")
                COMP_CWORD=$radp_vf_cword
                COMP_LINE="${radp_vf_words[*]}"
                COMP_POINT=${#COMP_LINE}
                _RADP_VF_DELEGATED=1 _radp_vf
            else
                # Fallback if radp-vf completion not loaded
                COMPREPLY=($(compgen -W "completion dump-config generate info init list template validate version vg --help" -- "$cur"))
            fi
            ;;
        'vf '*)
            # Delegate vf subcommands to radp-vf completion
            if type _radp_vf &>/dev/null; then
                # Set config from homelabctl config if not in command line
                local _hctl_vf_config_dir
                _hctl_vf_config_dir="$(_homelabctl_vf_config_dir)"
                [[ -n "$_hctl_vf_config_dir" ]] && export RADP_VAGRANT_CONFIG_DIR="$_hctl_vf_config_dir"
                local _hctl_vf_env
                _hctl_vf_env="$(_homelabctl_vf_env)"
                [[ -n "$_hctl_vf_env" ]] && export RADP_VAGRANT_ENV="$_hctl_vf_env"
                local radp_vf_words=("radp-vf" "${words[@]:2}")
                local radp_vf_cword=$((cword - 1))
                COMP_WORDS=("${radp_vf_words[@]}")
                COMP_CWORD=$radp_vf_cword
                COMP_LINE="${radp_vf_words[*]}"
                COMP_POINT=${#COMP_LINE}
                _RADP_VF_DELEGATED=1 _radp_vf
            else
                COMPREPLY=()
            fi
            ;;
        *)
            COMPREPLY=()
            ;;
    esac
}

complete -F _homelabctl homelabctl
