#compdef radp-vf

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

# Helper: Resolve config directory for completion
_radp_vf_comp_config_dir() {
    local config_dir=""
    
    # Priority 1: Check global variable from top-level opt_args
    # (set by _radp_vf when it processes -c/--config before entering subcommand)
    if [[ -n "${_RADP_VF_OPT_CONFIG:-}" ]]; then
        config_dir="$_RADP_VF_OPT_CONFIG"
    fi
    
    # Priority 2: Search words array (for subcommand-level -c/--config)
    if [[ -z "$config_dir" ]]; then
        local i
        for ((i = 1; i < ${#words[@]}; i++)); do
            case "${words[i]}" in
                -c|--config)
                    config_dir="${words[i+1]}"
                    break
                    ;;
                -c=*|--config=*)
                    config_dir="${words[i]#*=}"
                    break
                    ;;
            esac
        done
    fi
    
    # Priority 3: Environment variable
    if [[ -z "$config_dir" ]]; then
        config_dir="${RADP_VAGRANT_CONFIG_DIR:-}"
    fi
    
    # Priority 4: Current directory if it has vagrant.yaml
    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() {
    # Priority 1: Check global variable from top-level opt_args
    if [[ -n "${_RADP_VF_OPT_ENV:-}" ]]; then
        echo "$_RADP_VF_OPT_ENV"
        return
    fi
    
    # Priority 2: Search words array (for subcommand-level -e/--env)
    local i
    for ((i = 1; i < ${#words[@]}; i++)); do
        case "${words[i]}" in
            -e|--env)
                echo "${words[i+1]}"
                return
                ;;
            -e=*|--env=*)
                echo "${words[i]#*=}"
                return
                ;;
        esac
    done
    
    # Priority 3: Environment variable
    echo "${RADP_VAGRANT_ENV:-}"
}

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

# Completion function for cluster names
_radp_vf_clusters() {
    local config_dir env_override clusters
    config_dir="$(_radp_vf_comp_config_dir)"
    env_override="$(_radp_vf_comp_env)"
    if [[ -n "$config_dir" ]]; then
        clusters="$(_radp_vf_ruby_completion "$config_dir" "$env_override" "clusters")"
        if [[ -n "$clusters" ]]; then
            local -a cluster_array
            cluster_array=(${(f)clusters})
            _describe "cluster" cluster_array
        fi
    fi
}

# Completion function for guest IDs
_radp_vf_guests() {
    local config_dir env_override cluster_val guest_ids
    config_dir="$(_radp_vf_comp_config_dir)"
    env_override="$(_radp_vf_comp_env)"
    cluster_val="$(_radp_vf_comp_cluster)"
    if [[ -n "$config_dir" && -n "$cluster_val" ]]; then
        cluster_val="${cluster_val%%,*}"
        guest_ids="$(_radp_vf_ruby_completion "$config_dir" "$env_override" "guests" "$cluster_val")"
        if [[ -n "$guest_ids" ]]; then
            local -a guest_array
            guest_array=(${(f)guest_ids})
            _describe "guest-id" guest_array
        fi
    fi
}

# Completion function for vg args (vagrant commands + machine names)
_radp_vf_vg_args() {
    local config_dir env_override machines
    config_dir="$(_radp_vf_comp_config_dir)"
    env_override="$(_radp_vf_comp_env)"
    
    local -a vagrant_cmds
    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
        machines="$(_radp_vf_ruby_completion "$config_dir" "$env_override" "machines")"
        if [[ -n "$machines" ]]; then
            local -a machine_array
            machine_array=(${(f)machines})
            vagrant_cmds+=("$machine_array[@]")
        fi
    fi
    _describe "command" vagrant_cmds
}

# Completion function for machine names (used by list command)
_radp_vf_machines() {
    local config_dir env_override machines
    config_dir="$(_radp_vf_comp_config_dir)"
    env_override="$(_radp_vf_comp_env)"
    if [[ -n "$config_dir" ]]; then
        machines="$(_radp_vf_ruby_completion "$config_dir" "$env_override" "machines")"
        if [[ -n "$machines" ]]; then
            local -a machine_array
            machine_array=(${(f)machines})
            _describe "filter" machine_array
        fi
    fi
}

# Completion function for provision names (used by --provision-with)
_radp_vf_provisions() {
    local config_dir env_override provisions
    config_dir="$(_radp_vf_comp_config_dir)"
    env_override="$(_radp_vf_comp_env)"
    if [[ -n "$config_dir" ]]; then
        provisions="$(_radp_vf_ruby_completion "$config_dir" "$env_override" "provisions")"
        if [[ -n "$provisions" ]]; then
            local -a prov_array
            prov_array=(${(f)provisions})
            prov_array=(${prov_array//:/\\:})
            _describe "provision" prov_array
        fi
    fi
}

_radp_vf_completion() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '(-c --config)'{-c,--config}'[Configuration directory]:dir:_files -/' \
        '(-e --env)'{-e,--env}'[Override environment name]:name:' \
        '1:shell:(bash zsh)'
}

_radp_vf_dump_config() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '(-c --config)'{-c,--config}'[Configuration directory]:dir:_files -/' \
        '(-e --env)'{-e,--env}'[Override environment name]:name:' \
        '(-f --format)'{-f,--format}'[Output format: json or yaml (default: json)]:type:' \
        '(-o --output)'{-o,--output}'[Output file path]:file:' \
        '1:filter:_files'
}

_radp_vf_generate() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '(-c --config)'{-c,--config}'[Configuration directory]:dir:_files -/' \
        '(-e --env)'{-e,--env}'[Override environment name]:name:' \
        '1:output:_files'
}

_radp_vf_info() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '(-c --config)'{-c,--config}'[Configuration directory]:dir:_files -/' \
        '(-e --env)'{-e,--env}'[Override environment name]:name:' \
        '*:file:_files'
}

_radp_vf_init() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '(-c --config)'{-c,--config}'[Configuration directory]:dir:_files -/' \
        '(-e --env)'{-e,--env}'[Override environment name]:name:' \
        '(-t --template)'{-t,--template}'[Use a template (default: base)]:name:' \
        '--set[<var>=<value>~ Set template variable (can be repeated)]:var:' \
        '--force[Overwrite existing files]' \
        '--dry-run[Show what would be created without making changes]' \
        '1:dir:_files'
}

_radp_vf_list() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '(-c --config)'{-c,--config}'[Configuration directory]:dir:_files -/' \
        '(-e --env)'{-e,--env}'[Override environment name]:name:' \
        '(-a --all)'{-a,--all}'[Show all detailed info]' \
        '(-p --provisions)'{-p,--provisions}'[Show provisions only]' \
        '(-s --synced-folders)'{-s,--synced-folders}'[Show synced folders only]' \
        '(-t --triggers)'{-t,--triggers}'[Show triggers only]' \
        '(-S --status)'{-S,--status}'[Show VM runtime status]' \
        '*:filter:_radp_vf_machines'
}

_radp_vf_template() {
    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=(
                'list:List available project templates'
                'show:Show template details and variables'
            )
            _describe 'subcommand' commands
            ;;
        args)
            local cmd_func="_radp_vf_template_${words[1]//-/_}"
            if (( $+functions[$cmd_func] )); then
                $cmd_func
            else
                _files
            fi
            ;;
    esac
}

_radp_vf_template_list() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '(-c --config)'{-c,--config}'[Configuration directory]:dir:_files -/' \
        '(-e --env)'{-e,--env}'[Override environment name]:name:' \
        '*:file:_files'
}

_radp_vf_template_show() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '(-c --config)'{-c,--config}'[Configuration directory]:dir:_files -/' \
        '(-e --env)'{-e,--env}'[Override environment name]:name:' \
        '1:name:_files'
}

_radp_vf_upgrade() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '(-c --config)'{-c,--config}'[Configuration directory]:dir:_files -/' \
        '(-e --env)'{-e,--env}'[Override environment name]:name:' \
        '--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'
}

_radp_vf_validate() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '(-c --config)'{-c,--config}'[Configuration directory]:dir:_files -/' \
        '(-e --env)'{-e,--env}'[Override environment name]:name:' \
        '*:file:_files'
}

_radp_vf_version() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '(-c --config)'{-c,--config}'[Configuration directory]:dir:_files -/' \
        '(-e --env)'{-e,--env}'[Override environment name]:name:' \
        '*:file:_files'
}

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

    _arguments -C -s \
        '(-h --help)'{-h,--help}'[Show help]' \
        '(-c --config)'{-c,--config}'[Configuration directory]:dir:_files -/' \
        '(-e --env)'{-e,--env}'[Override environment name]:name:' \
        '(-C --cluster)'{-C,--cluster}'[Cluster names (comma-separated for multiple)]:names:_radp_vf_clusters' \
        '(-G --guest-ids)'{-G,--guest-ids}'[Guest IDs (comma-separated, requires --cluster)]:ids:_radp_vf_guests' \
        '*:: :->vagrant_args'

    case "$state" in
        vagrant_args)
            if (( $+functions[_vagrant] )); then
                words=("vagrant" "${words[@]}")
                ((CURRENT++))
                _vagrant
            else
                _radp_vf_vg_args
            fi
            # Always add machine names — _vagrant does not complete them
            _radp_vf_machines
            # Complete provision names for --provision-with
            if [[ $CURRENT -gt 1 && "${words[CURRENT-1]}" == --provision-with ]]; then
                _radp_vf_provisions
            elif [[ "${words[CURRENT]}" == --provision-with=* ]]; then
                compset -P '*='
                _radp_vf_provisions
            fi
            ;;
    esac
}

_radp_vf() {
    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)]' \
        '(-c --config)'{-c,--config}'[Configuration directory]:dir:_files -/' \
        '(-e --env)'{-e,--env}'[Override environment name]:name:' \
        && 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)]' \
        '(-c --config)'{-c,--config}'[Configuration directory]:dir:_files -/' \
        '(-e --env)'{-e,--env}'[Override environment name]:name:' \
        '1: :->command' \
        '*:: :->args'

    case "$state" in
        command)
            local commands=(
                'completion:Generate shell completion script'
                'dump-config:Dump merged configuration (use -o for file output)'
                'generate:Generate standalone Vagrantfile'
                'info:Show environment and configuration info'
                'init:Initialize a new project with sample configuration'
                'list:List clusters and guests from configuration'
                'template:Manage template'
                'upgrade:Upgrade radp-vf to the latest version'
                'validate:Validate YAML configuration files'
                'version:Show radp-vagrant-framework version'
                'vg:Run vagrant command with framework'
            )
            _describe 'command' commands
            ;;
        args)
            typeset -g _RADP_VF_OPT_CONFIG="${opt_args[-c]:-${opt_args[--config]:-}}"
            typeset -g _RADP_VF_OPT_ENV="${opt_args[-e]:-${opt_args[--env]:-}}"
            local cmd_func="_radp_vf_${words[1]//-/_}"
            if (( $+functions[$cmd_func] )); then
                $cmd_func
            else
                _files
            fi
            ;;
    esac
}

_radp_vf "$@"
