#compdef homelabctl

# 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
}


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

_homelabctl_arg_setup_deps_name() {
    local completions=($(_homelabctl_complete_packages 2>/dev/null))
    _describe 'name' completions
}

_homelabctl_arg_setup_info_name() {
    local completions=($(_homelabctl_complete_packages 2>/dev/null))
    _describe 'name' completions
}

_homelabctl_arg_setup_install_name() {
    local completions=($(_homelabctl_complete_packages 2>/dev/null))
    _describe 'name' completions
}

_homelabctl_opt_setup_list_category() {
    local completions=($(_homelabctl_complete_categories 2>/dev/null))
    _describe 'name' completions
}

_homelabctl_arg_setup_profile_apply_name() {
    local completions=($(_homelabctl_complete_profiles 2>/dev/null))
    _describe 'name' completions
}

_homelabctl_arg_setup_profile_show_name() {
    local completions=($(_homelabctl_complete_profiles 2>/dev/null))
    _describe 'name' completions
}

_homelabctl_arg_setup_uninstall_name() {
    local completions=($(_homelabctl_complete_packages 2>/dev/null))
    _describe 'name' completions
}

_homelabctl_completion() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '1:shell:(bash zsh)'
}

_homelabctl_gitlab() {
    local context state state_descr line
    typeset -A opt_args

    _arguments -C -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '1: :->command' \
        '*:: :->args'

    case "$state" in
        command)
            local commands=(
                'backup:Manage backup'
                'healthcheck:Run GitLab health checks'
                'init:Initialize GitLab after installation'
                'install:Install GitLab (gitlab-ce or gitlab-ee) via linux_package'
                'reset-password:Reset GitLab user password'
                'restart:Restart GitLab services'
                'restore:Restore GitLab data and/or configuration from backup'
                'runner:Manage runner'
                'start:Start GitLab services'
                'status:Show GitLab status and version info'
                'stop:Stop GitLab services'
            )
            _describe 'subcommand' commands
            ;;
        args)
            local cmd_func="_homelabctl_gitlab_${words[1]//-/_}"
            if (( $+functions[$cmd_func] )); then
                $cmd_func
            else
                _files
            fi
            ;;
    esac
}

_homelabctl_gitlab_backup() {
    local context state state_descr line
    typeset -A opt_args

    _arguments -C -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '1: :->command' \
        '*:: :->args'

    case "$state" in
        command)
            local commands=(
                'cleanup:Clean old GitLab backups'
                'create:Create GitLab backup (data and/or configuration)'
                'list:List available GitLab backups'
            )
            _describe 'subcommand' commands
            ;;
        args)
            local cmd_func="_homelabctl_gitlab_backup_${words[1]//-/_}"
            if (( $+functions[$cmd_func] )); then
                $cmd_func
            else
                _files
            fi
            ;;
    esac
}

_homelabctl_gitlab_backup_cleanup() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '--keep-days[Days to keep backups (default: from config)]:n:' \
        '--dry-run[Show what would be done]' \
        '*:file:_files'
}

_homelabctl_gitlab_backup_create() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '--target[Target directory for backup]:path:' \
        '--type[Backup type: all, data, config (default: all)]:type:' \
        '--skip-remote[Skip copy to remote/NAS location]' \
        '--dry-run[Show what would be done]' \
        '*:file:_files'
}

_homelabctl_gitlab_backup_list() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '--type[Backup type: all, data, config (default: all)]:type:' \
        '*:file:_files'
}

_homelabctl_gitlab_healthcheck() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '--verbose[Show detailed output]' \
        '--check-secrets[Also run secrets doctor]' \
        '--dry-run[Show what would be done]' \
        '*:file:_files'
}

_homelabctl_gitlab_init() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '--user-config[User'\''s custom GitLab config file (e.g., /data/homelab_gitlab.rb)]:path:' \
        '--backup-schedule[Backup crontab schedule (default: "0 4 * * *")]:cron:' \
        '--skip-crontab[Skip automatic backup crontab setup]' \
        '--skip-reconfigure[Skip reconfigure and restart (only setup directories and crontab)]' \
        '--dry-run[Show what would be done]' \
        '*:file:_files'
}

_homelabctl_gitlab_install() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '(-t --type)'{-t,--type}'[GitLab type: gitlab-ce or gitlab-ee (default: gitlab-ce)]:type:' \
        '(-v --version)'{-v,--version}'[GitLab version (default: latest)]:ver:' \
        '--data-dir[Custom data directory (symlink target)]:path:' \
        '--skip-postfix[Skip postfix installation]' \
        '--dry-run[Show what would be done]' \
        '*:file:_files'
}

_homelabctl_gitlab_reset_password() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '--force[Skip confirmation prompt]' \
        '--dry-run[Show what would be done]' \
        '1:username:_files'
}

_homelabctl_gitlab_restart() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '--service[Specific service to restart (puma, sidekiq, etc.)]:name:' \
        '--dry-run[Show what would be done]' \
        '*:file:_files'
}

_homelabctl_gitlab_restore() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '--type[Restore type: all, data, config (default: all)]:type:' \
        '--source[Source directory to search for backups]:path:' \
        '--force[Skip confirmation prompts]' \
        '--dry-run[Show what would be done]' \
        '1:backup_file:_files'
}

_homelabctl_gitlab_runner() {
    local context state state_descr line
    typeset -A opt_args

    _arguments -C -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '1: :->command' \
        '*:: :->args'

    case "$state" in
        command)
            local commands=(
                'install:Install GitLab Runner'
            )
            _describe 'subcommand' commands
            ;;
        args)
            local cmd_func="_homelabctl_gitlab_runner_${words[1]//-/_}"
            if (( $+functions[$cmd_func] )); then
                $cmd_func
            else
                _files
            fi
            ;;
    esac
}

_homelabctl_gitlab_runner_install() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '(-v --version)'{-v,--version}'[GitLab Runner version (default: latest)]:ver:' \
        '--dry-run[Show what would be done]' \
        '*:file:_files'
}

_homelabctl_gitlab_start() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '--service[Specific service to start (puma, sidekiq, etc.)]:name:' \
        '--dry-run[Show what would be done]' \
        '*:file:_files'
}

_homelabctl_gitlab_status() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '--services[Show all service status details]' \
        '*:file:_files'
}

_homelabctl_gitlab_stop() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '--service[Specific service to stop (puma, sidekiq, etc.)]:name:' \
        '--dry-run[Show what would be done]' \
        '*:file:_files'
}

_homelabctl_init() {
    local context state state_descr line
    typeset -A opt_args

    _arguments -C -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '1: :->command' \
        '*:: :->args'

    case "$state" in
        command)
            local commands=(
                'all:Initialize all user configuration directories'
                'k8s:Initialize k8s user configuration directory'
                'setup:Initialize setup user configuration directory'
                'vf:Initialize VF configuration directory'
            )
            _describe 'subcommand' commands
            ;;
        args)
            local cmd_func="_homelabctl_init_${words[1]//-/_}"
            if (( $+functions[$cmd_func] )); then
                $cmd_func
            else
                _files
            fi
            ;;
    esac
}

_homelabctl_init_all() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '--force[Overwrite existing files]' \
        '--dry-run[Show what would be created without making changes]' \
        '*:file:_files'
}

_homelabctl_init_k8s() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '--force[Overwrite existing files]' \
        '--dry-run[Show what would be created without making changes]' \
        '*:file:_files'
}

_homelabctl_init_setup() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '--force[Overwrite existing files]' \
        '--dry-run[Show what would be created without making changes]' \
        '*:file:_files'
}

_homelabctl_init_vf() {
    _files
}

_homelabctl_k8s() {
    local context state state_descr line
    typeset -A opt_args

    _arguments -C -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '1: :->command' \
        '*:: :->args'

    case "$state" in
        command)
            local commands=(
                'addon:Manage addon'
                'backup:Manage backup'
                'health:Check Kubernetes cluster health'
                'init:Manage init'
                'install:Install Kubernetes (kubeadm, kubelet, kubectl)'
                'token:Manage token'
                'upgrade:Manage upgrade'
            )
            _describe 'subcommand' commands
            ;;
        args)
            local cmd_func="_homelabctl_k8s_${words[1]//-/_}"
            if (( $+functions[$cmd_func] )); then
                $cmd_func
            else
                _files
            fi
            ;;
    esac
}

_homelabctl_k8s_addon() {
    local context state state_descr line
    typeset -A opt_args

    _arguments -C -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '1: :->command' \
        '*:: :->args'

    case "$state" in
        command)
            local commands=(
                'install:Install a Kubernetes addon'
                'list:List available Kubernetes addons'
                'profile:Manage profile'
                'quickstart:Install recommended addons (alias for '\''profile apply quickstart'\'')'
                'uninstall:Uninstall a Kubernetes addon'
            )
            _describe 'subcommand' commands
            ;;
        args)
            local cmd_func="_homelabctl_k8s_addon_${words[1]//-/_}"
            if (( $+functions[$cmd_func] )); then
                $cmd_func
            else
                _files
            fi
            ;;
    esac
}

_homelabctl_k8s_addon_install() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '(-v --version)'{-v,--version}'[Addon version (uses default if not specified)]:ver:' \
        '(-f --values)'{-f,--values}'[Custom values file for helm]:file:' \
        '--dry-run[Show what would be done]' \
        '1:name:_files'
}

_homelabctl_k8s_addon_list() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '--installed[Show only installed addons]' \
        '*:file:_files'
}

_homelabctl_k8s_addon_profile() {
    local context state state_descr line
    typeset -A opt_args

    _arguments -C -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '1: :->command' \
        '*:: :->args'

    case "$state" in
        command)
            local commands=(
                'apply:Apply an addon profile (install multiple addons)'
                'list:List available addon profiles'
                'show:Show addon profile details'
            )
            _describe 'subcommand' commands
            ;;
        args)
            local cmd_func="_homelabctl_k8s_addon_profile_${words[1]//-/_}"
            if (( $+functions[$cmd_func] )); then
                $cmd_func
            else
                _files
            fi
            ;;
    esac
}

_homelabctl_k8s_addon_profile_apply() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '--dry-run[Show what would be installed]' \
        '--continue[Continue on error]' \
        '--skip-installed[Skip already installed addons]' \
        '1:name:_files'
}

_homelabctl_k8s_addon_profile_list() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '--names-only[Output profile names only (for completion)]' \
        '*:file:_files'
}

_homelabctl_k8s_addon_profile_show() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '1:name:_files'
}

_homelabctl_k8s_addon_quickstart() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '--dry-run[Show what would be done]' \
        '--continue[Continue on error]' \
        '--skip-installed[Skip already installed addons]' \
        '*:file:_files'
}

_homelabctl_k8s_addon_uninstall() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '--dry-run[Show what would be done]' \
        '1:name:_files'
}

_homelabctl_k8s_backup() {
    local context state state_descr line
    typeset -A opt_args

    _arguments -C -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '1: :->command' \
        '*:: :->args'

    case "$state" in
        command)
            local commands=(
                'cleanup:Clean old etcd backups'
                'create:Create etcd backup'
                'list:List available etcd backups'
                'restore:Restore etcd from backup'
            )
            _describe 'subcommand' commands
            ;;
        args)
            local cmd_func="_homelabctl_k8s_backup_${words[1]//-/_}"
            if (( $+functions[$cmd_func] )); then
                $cmd_func
            else
                _files
            fi
            ;;
    esac
}

_homelabctl_k8s_backup_cleanup() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '--keep-days[Days to keep backups (default: from config)]:n:' \
        '(-d --dir)'{-d,--dir}'[Backup directory (default: /var/opt/k8s/backups/etcd)]:path:' \
        '--dry-run[Show what would be done]' \
        '*:file:_files'
}

_homelabctl_k8s_backup_create() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '(-d --dir)'{-d,--dir}'[Backup directory (default: /var/opt/k8s/backups/etcd)]:path:' \
        '--dry-run[Show what would be done]' \
        '*:file:_files'
}

_homelabctl_k8s_backup_list() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '(-d --dir)'{-d,--dir}'[Backup directory (default: /var/opt/k8s/backups/etcd)]:path:' \
        '*:file:_files'
}

_homelabctl_k8s_backup_restore() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '--data-dir[etcd data directory (default: /var/lib/etcd)]:path:' \
        '--dry-run[Show what would be done]' \
        '--force[Skip confirmation prompt]' \
        '1:file:_files'
}

_homelabctl_k8s_health() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '--verbose[Show detailed output]' \
        '*:file:_files'
}

_homelabctl_k8s_init() {
    local context state state_descr line
    typeset -A opt_args

    _arguments -C -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '1: :->command' \
        '*:: :->args'

    case "$state" in
        command)
            local commands=(
                'master:Initialize Kubernetes master node'
                'worker:Initialize Kubernetes worker node and join cluster'
            )
            _describe 'subcommand' commands
            ;;
        args)
            local cmd_func="_homelabctl_k8s_init_${words[1]//-/_}"
            if (( $+functions[$cmd_func] )); then
                $cmd_func
            else
                _files
            fi
            ;;
    esac
}

_homelabctl_k8s_init_master() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '(-a --apiserver-advertise-address)'{-a,--apiserver-advertise-address}'[]:ip:' \
        '(-p --pod-network-cidr)'{-p,--pod-network-cidr}'[Pod network CIDR (default: 10.244.0.0/16)]:cidr:' \
        '(-e --control-plane-endpoint)'{-e,--control-plane-endpoint}'[Shared API endpoint for HA (e.g., k8s-api.homelab:6443 or VIP:6443)]:endpoint:' \
        '--dry-run[Show what would be done]' \
        '*:file:_files'
}

_homelabctl_k8s_init_worker() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '(-c --control-plane)'{-c,--control-plane}'[]:host:port:' \
        '(-t --token)'{-t,--token}'[Join token (optional, will retrieve from master if not provided)]:token:' \
        '--discovery-token-ca-cert-hash[CA cert hash (optional, will retrieve if not provided)]:hash:' \
        '(-u --ssh-user)'{-u,--ssh-user}'[SSH user for connecting to master (default: from config, typically root)]:user:' \
        '(-i --ssh-key)'{-i,--ssh-key}'[SSH private key for connecting to master]:path:' \
        '--dry-run[Show what would be done]' \
        '*:file:_files'
}

_homelabctl_k8s_install() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '(-t --type)'{-t,--type}'[Install type: kubeadm or minikube (default: kubeadm)]:type:' \
        '(-v --version)'{-v,--version}'[Kubernetes version (default: 1.30)]:ver:' \
        '--skip-prerequisites[Skip prerequisites configuration]' \
        '--skip-container-runtime[Skip container runtime installation]' \
        '--dry-run[Show what would be done]' \
        '*:file:_files'
}

_homelabctl_k8s_token() {
    local context state state_descr line
    typeset -A opt_args

    _arguments -C -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '1: :->command' \
        '*:: :->args'

    case "$state" in
        command)
            local commands=(
                'create:Create a new Kubernetes join token'
                'get:Get current valid Kubernetes token'
            )
            _describe 'subcommand' commands
            ;;
        args)
            local cmd_func="_homelabctl_k8s_token_${words[1]//-/_}"
            if (( $+functions[$cmd_func] )); then
                $cmd_func
            else
                _files
            fi
            ;;
    esac
}

_homelabctl_k8s_token_create() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '--print-join-command[Print full join command after creation]' \
        '*:file:_files'
}

_homelabctl_k8s_token_get() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '--create[Create new token if no valid token exists]' \
        '--join-command[Print full join command instead of just token]' \
        '*:file:_files'
}

_homelabctl_k8s_upgrade() {
    local context state state_descr line
    typeset -A opt_args

    _arguments -C -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '1: :->command' \
        '*:: :->args'

    case "$state" in
        command)
            local commands=(
                'apply:Upgrade the first control plane node (runs kubeadm upgrade apply + drain + kubelet upgrade + uncordon)'
                'cluster:Orchestrate a full cluster upgrade (first CP -> other CPs -> workers) via SSH'
                'node:Upgrade an additional control plane or worker node (runs kubeadm upgrade node)'
                'plan:Show kubeadm upgrade plan (run on the first control plane node)'
            )
            _describe 'subcommand' commands
            ;;
        args)
            local cmd_func="_homelabctl_k8s_upgrade_${words[1]//-/_}"
            if (( $+functions[$cmd_func] )); then
                $cmd_func
            else
                _files
            fi
            ;;
    esac
}

_homelabctl_k8s_upgrade_apply() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '--ignore-preflight-errors[Comma-separated preflight errors to ignore (e.g., CoreDNSUnsupportedPlugins,CoreDNSMigration)]:list:' \
        '(-y --yes)'{-y,--yes}'[Skip confirmation prompt]' \
        '--dry-run[Show what would be done]' \
        '1:version:_files'
}

_homelabctl_k8s_upgrade_cluster() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '--ignore-preflight-errors[Comma-separated preflight errors to ignore (passed to every node)]:list:' \
        '(-u --ssh-user)'{-u,--ssh-user}'[SSH user for remote nodes (default: from config)]:user:' \
        '(-i --ssh-key)'{-i,--ssh-key}'[SSH private key for remote nodes]:path:' \
        '(-y --yes)'{-y,--yes}'[Skip confirmation prompt]' \
        '--dry-run[Show what would be done]' \
        '1:version:_files'
}

_homelabctl_k8s_upgrade_node() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '(-v --version)'{-v,--version}'[]:ver:' \
        '(-r --role)'{-r,--role}'[Node role: control-plane or worker (default: auto-detect)]:role:' \
        '--ignore-preflight-errors[Comma-separated preflight errors to ignore]:list:' \
        '--skip-drain[Skip local drain/uncordon (used when orchestrated from master)]' \
        '(-y --yes)'{-y,--yes}'[Skip confirmation prompt]' \
        '--dry-run[Show what would be done]' \
        '*:file:_files'
}

_homelabctl_k8s_upgrade_plan() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '--ignore-preflight-errors[Comma-separated preflight errors to ignore (e.g., CoreDNSUnsupportedPlugins,CoreDNSMigration)]:list:' \
        '*:file:_files'
}

_homelabctl_setup() {
    local context state state_descr line
    typeset -A opt_args

    _arguments -C -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '1: :->command' \
        '*:: :->args'

    case "$state" in
        command)
            local commands=(
                'configure:Manage configure'
                'deps:Show package dependency tree'
                'info:Show package details'
                'install:Install a software package'
                'list:List available packages'
                'profile:Manage profile'
                'uninstall:Uninstall a software package'
            )
            _describe 'subcommand' commands
            ;;
        args)
            local cmd_func="_homelabctl_setup_${words[1]//-/_}"
            if (( $+functions[$cmd_func] )); then
                $cmd_func
            else
                _files
            fi
            ;;
    esac
}

_homelabctl_setup_configure() {
    local context state state_descr line
    typeset -A opt_args

    _arguments -C -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '1: :->command' \
        '*:: :->args'

    case "$state" in
        command)
            local commands=(
                'chrony:Configure chrony for time synchronization'
                'docker:Manage docker'
                'expand-lvm:Expand LVM partition and filesystem to use all available disk space'
                'gpg-import:Import GPG keys into user keyring'
                'gpg-preset:Preset GPG passphrase in gpg-agent cache for non-interactive operations'
                'list:List available system configurations'
                'yadm:Clone dotfiles repository using yadm'
            )
            _describe 'subcommand' commands
            ;;
        args)
            local cmd_func="_homelabctl_setup_configure_${words[1]//-/_}"
            if (( $+functions[$cmd_func] )); then
                $cmd_func
            else
                _files
            fi
            ;;
    esac
}

_homelabctl_setup_configure_chrony() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '--servers[Comma-separated NTP servers (e.g., "ntp.aliyun.com,ntp1.aliyun.com")]:list:' \
        '--pool[NTP pool to use if servers not specified (default: pool.ntp.org)]:pool:' \
        '--timezone[Timezone to set (e.g., "Asia/Shanghai")]:tz:' \
        '--sync-now[Force immediate time sync after configuration]' \
        '--dry-run[Show what would be done without making changes]' \
        '*:file:_files'
}

_homelabctl_setup_configure_docker() {
    local context state state_descr line
    typeset -A opt_args

    _arguments -C -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '1: :->command' \
        '*:: :->args'

    case "$state" in
        command)
            local commands=(
                'acceleration:Configure Docker acceleration (proxy or registry mirrors)'
                'rootless:Configure Docker for non-root user access'
            )
            _describe 'subcommand' commands
            ;;
        args)
            local cmd_func="_homelabctl_setup_configure_docker_${words[1]//-/_}"
            if (( $+functions[$cmd_func] )); then
                $cmd_func
            else
                _files
            fi
            ;;
    esac
}

_homelabctl_setup_configure_docker_acceleration() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '--proxy[HTTP/HTTPS proxy URL (e.g., http://192.168.1.1:8080)]:url:' \
        '--https-proxy[HTTPS proxy URL (default: same as --proxy)]:url:' \
        '--no-proxy[Comma-separated hosts to bypass proxy (default: localhost,127.0.0.1)]:list:' \
        '--mirrors[Comma-separated registry mirror URLs]:list:' \
        '--remove-proxy[Remove existing proxy configuration]' \
        '--dry-run[Show what would be done without making changes]' \
        '*:file:_files'
}

_homelabctl_setup_configure_docker_rootless() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '(-u --user)'{-u,--user}'[Target user (default: current user)]:user:' \
        '--dry-run[Show what would be done without making changes]' \
        '*:file:_files'
}

_homelabctl_setup_configure_expand_lvm() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '--partition[LVM partition to expand (e.g., /dev/sda3). Auto-detected if not specified.]:dev:' \
        '--vg[Volume group name. Auto-detected if not specified.]:name:' \
        '--lv[Logical volume to expand. Auto-detected if not specified.]:name:' \
        '--dry-run[Show what would be done without making changes]' \
        '*:file:_files'
}

_homelabctl_setup_configure_gpg_import() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '--public-key[GPG public key content (ASCII-armored)]:content:' \
        '--public-key-file[Path to GPG public key file]:file:' \
        '--secret-key-file[Path to GPG secret key file]:file:' \
        '--passphrase[Passphrase for secret key]:pass:' \
        '--passphrase-file[Path to file containing passphrase]:file:' \
        '--key-id[GPG key ID to fetch from keyserver]:id:' \
        '--keyserver[Keyserver URL (default: keys.openpgp.org)]:url:' \
        '--trust-level[Trust level (2=unknown, 3=marginal, 4=full, 5=ultimate)]:level:' \
        '--ownertrust-file[Path to ownertrust file]:file:' \
        '--user[Target user (default: current user, requires sudo for other users)]:name:' \
        '--dry-run[Show what would be done without making changes]' \
        '*:file:_files'
}

_homelabctl_setup_configure_gpg_preset() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '--key-uid[Key UID (email) to identify the key (e.g., user@example.com)]:uid:' \
        '--passphrase[Passphrase content]:pass:' \
        '--passphrase-file[Path to file containing passphrase]:file:' \
        '--user[Target user (default: current user, requires sudo for other users)]:name:' \
        '--no-auto-config[Skip auto-configuring gpg-agent.conf with allow-preset-passphrase]' \
        '--dry-run[Show what would be done without making changes]' \
        '*:file:_files'
}

_homelabctl_setup_configure_list() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '*:file:_files'
}

_homelabctl_setup_configure_yadm() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '--repo-url[Dotfiles repository URL (HTTPS or SSH format)]:url:' \
        '--class[Set yadm class before clone]:class:' \
        '--https-user[Username for HTTPS authentication]:user:' \
        '--https-token[Personal access token for HTTPS authentication]:token:' \
        '--https-token-file[Path to file containing access token]:file:' \
        '--ssh-key-file[Path to SSH private key file]:file:' \
        '--ssh-host[Override SSH hostname/IP (for private servers)]:host:' \
        '--ssh-port[Override SSH port (default 22)]:port:' \
        '--user[Target user (default: current user, requires sudo for other users)]:name:' \
        '--bootstrap[Run yadm bootstrap after clone]' \
        '--decrypt[Run yadm decrypt after clone (requires GPG key imported)]' \
        '--strict-host-key[Enable strict host key checking (default: disabled for automation)]' \
        '--dry-run[Show what would be done without making changes]' \
        '*:file:_files'
}

_homelabctl_setup_deps() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '--reverse[Show reverse dependencies (packages that depend on this one)]' \
        '1:name:_homelabctl_arg_setup_deps_name'
}

_homelabctl_setup_info() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '--all-platforms[Show dependencies for all platforms]' \
        '1:name:_homelabctl_arg_setup_info_name'
}

_homelabctl_setup_install() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '(-v --version)'{-v,--version}'[Specific version (default: latest)]:ver:' \
        '--dry-run[Show what would be installed without installing]' \
        '--no-deps[Skip automatic dependency installation]' \
        '1:name:_homelabctl_arg_setup_install_name'
}

_homelabctl_setup_list() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '(-c --category)'{-c,--category}'[Filter by category]:name:_homelabctl_opt_setup_list_category' \
        '--installed[Show only installed packages]' \
        '--categories[List available categories]' \
        '--names-only[Output package names only (for completion)]' \
        '--category-names[Output category names only (for completion)]' \
        '*:file:_files'
}

_homelabctl_setup_profile() {
    local context state state_descr line
    typeset -A opt_args

    _arguments -C -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '1: :->command' \
        '*:: :->args'

    case "$state" in
        command)
            local commands=(
                'apply:Apply a setup profile (install multiple packages)'
                'list:List available setup profiles'
                'show:Show profile details'
            )
            _describe 'subcommand' commands
            ;;
        args)
            local cmd_func="_homelabctl_setup_profile_${words[1]//-/_}"
            if (( $+functions[$cmd_func] )); then
                $cmd_func
            else
                _files
            fi
            ;;
    esac
}

_homelabctl_setup_profile_apply() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '--dry-run[Show what would be installed]' \
        '--continue[Continue on error]' \
        '--skip-installed[Skip already installed packages]' \
        '--no-deps[Skip automatic dependency installation]' \
        '1:name:_homelabctl_arg_setup_profile_apply_name'
}

_homelabctl_setup_profile_list() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '--names-only[Output profile names only (for completion)]' \
        '*:file:_files'
}

_homelabctl_setup_profile_show() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '1:name:_homelabctl_arg_setup_profile_show_name'
}

_homelabctl_setup_uninstall() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '--purge[Remove configuration files as well]' \
        '--dry-run[Show what would be uninstalled without uninstalling]' \
        '1:name:_homelabctl_arg_setup_uninstall_name'
}

_homelabctl_upgrade() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '--check[Only check for updates]' \
        '--force[Force upgrade even if at latest]' \
        '(-y --yes)'{-y,--yes}'[Skip confirmation prompt]' \
        '--version[Target specific version]:version:' \
        '*:file:_files'
}

_homelabctl_version() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '*:file:_files'
}

_homelabctl_vf() {
    _files
}

_homelabctl() {
    local context state state_descr line
    typeset -A opt_args

    # Workaround: Handle option prefix completion explicitly
    # Without this, -<TAB> may fall through to command completion
    # because _arguments -C doesn't trigger option completion for
    # incomplete option prefixes when positional args are specified
    if [[ $CURRENT -eq 2 && "${words[CURRENT]}" == -* ]]; then
        _arguments -s \
            '(-h --help)'{-h,--help}'[Show help]' \
            '--version[Show version]' \
        '(-q --quiet)'{-q,--quiet}'[Enable quiet mode]' \
        '(-v --verbose)'{-v,--verbose}'[Enable verbose output]' \
        '--debug[Enable debug output]' \
        '--show-config[Show configuration]' \
        '--all[Show all (with --show-config)]' \
        '--json[Output as JSON (with --show-config)]' \
        && return
    fi

    _arguments -C -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '--version[Show version]' \
        '(-q --quiet)'{-q,--quiet}'[Enable quiet mode]' \
        '(-v --verbose)'{-v,--verbose}'[Enable verbose output]' \
        '--debug[Enable debug output]' \
        '--show-config[Show configuration]' \
        '--all[Show all (with --show-config)]' \
        '--json[Output as JSON (with --show-config)]' \
        '1: :->command' \
        '*:: :->args'

    case "$state" in
        command)
            local commands=(
                'completion:Generate shell completion script'
                'gitlab:Manage gitlab'
                'init:Manage init'
                'k8s:Manage k8s'
                'setup:Manage setup'
                'upgrade:Upgrade homelabctl to the latest version'
                'version:Show version information'
                'vf:Run radp-vagrant-framework commands (passthrough to radp-vf)'
            )
            _describe 'command' commands
            ;;
        args)
            local cmd_func="_homelabctl_${words[1]//-/_}"
            if (( $+functions[$cmd_func] )); then
                $cmd_func
            else
                _files
            fi
            ;;
    esac
}


# Override _homelabctl_vf to delegate to radp-vf's native completion
_homelabctl_vf() {
    # Set config from homelabctl config if not already set
    local _hctl_vf_config_dir _hctl_vf_env
    _hctl_vf_config_dir="$(_homelabctl_vf_config_dir)"
    [[ -n "$_hctl_vf_config_dir" ]] && export RADP_VAGRANT_CONFIG_DIR="$_hctl_vf_config_dir"
    _hctl_vf_env="$(_homelabctl_vf_env)"
    [[ -n "$_hctl_vf_env" ]] && export RADP_VAGRANT_ENV="$_hctl_vf_env"

    # Replace "vf" with "radp-vf" so _radp-vf sees the right command name
    words[1]="radp-vf"

    # Delegate to radp-vf completion (file _radp-vf, autoloaded by compinit)
    if (( $+functions[_radp-vf] )); then
        _radp-vf
    else
        _files
    fi
}

_homelabctl "$@"
