#compdef kdebug
# kdebug zsh completion
# Install: kdebug --completions zsh > ~/.zsh/completions/_kdebug
# Or: source <(kdebug --completions zsh)

_kdebug_kubectl_args() {
    local args=""
    [[ -n "${opt_args[--context]}" ]] && args="$args --context=${opt_args[--context]}"
    [[ -n "${opt_args[--kubeconfig]}" ]] && args="$args --kubeconfig=${opt_args[--kubeconfig]}"
    echo "$args"
}

_kdebug_contexts() {
    local -a contexts
    contexts=(${(f)"$(kubectl config get-contexts -o name 2>/dev/null)"})
    _describe 'context' contexts
}

_kdebug_namespaces() {
    local kubectl_args=$(_kdebug_kubectl_args)
    local -a namespaces
    namespaces=(${(f)"$(kubectl $kubectl_args get namespaces -o jsonpath='{range .items[*]}{.metadata.name}{"\n"}{end}' 2>/dev/null)"})
    _describe 'namespace' namespaces
}

_kdebug_pods() {
    local ns="${opt_args[-n]:-${opt_args[--namespace]:-default}}"
    local kubectl_args=$(_kdebug_kubectl_args)
    local -a pods
    pods=(${(f)"$(kubectl $kubectl_args get pods -n "$ns" -o jsonpath='{range .items[*]}{.metadata.name}{"\n"}{end}' 2>/dev/null)"})
    _describe 'pod' pods
}

_kdebug_controllers() {
    local ns="${opt_args[-n]:-${opt_args[--namespace]:-default}}"
    local kubectl_args=$(_kdebug_kubectl_args)
    local cur_word="${words[CURRENT]}"

    if [[ "$cur_word" == */* ]]; then
        # User typed TYPE/ - complete the name
        local ct="${cur_word%%/*}"
        local resource
        case "$ct" in
            deployment|deploy) resource="deployments" ;;
            statefulset|sts) resource="statefulsets" ;;
            daemonset|ds) resource="daemonsets" ;;
            *) resource="deployments" ;;
        esac
        local -a names
        names=(${(f)"$(kubectl $kubectl_args get "$resource" -n "$ns" -o jsonpath='{range .items[*]}{.metadata.name}{"\n"}{end}' 2>/dev/null)"})
        local -a completions
        for name in "${names[@]}"; do
            completions+=("${ct}/${name}")
        done
        compadd -Q -- "${completions[@]}"
    else
        # Complete the type prefix
        local -a prefixes
        prefixes=(
            'deployment/:Deployment'
            'deploy/:Deployment (short)'
            'statefulset/:StatefulSet'
            'sts/:StatefulSet (short)'
            'daemonset/:DaemonSet'
            'ds/:DaemonSet (short)'
        )
        _describe 'controller type' prefixes -S ''
    fi
}

_kdebug() {
    local -a shared_args
    shared_args=(
        '(-v --version)'{-v,--version}'[Show version and exit]'
        '(-h --help)'{-h,--help}'[Show help message]'
        '--pod[Pod name for direct selection]:pod:_kdebug_pods'
        '--controller[Controller as TYPE/NAME]:controller:_kdebug_controllers'
        '(-n --namespace)'{-n,--namespace}'[Kubernetes namespace]:namespace:_kdebug_namespaces'
        '--context[Kubernetes context to use]:context:_kdebug_contexts'
        '--kubeconfig[Path to kubeconfig file]:path:_files'
        '--container[Target container for process namespace sharing]:container:'
        '--debug-image[Debug container image]:image:'
        '--as-root[Run debug container as root]'
        '--verbose[Show kubectl commands being executed]'
        '--completions[Output shell completion script]:shell:(bash zsh fish)'
    )

    local -a debug_args
    debug_args=(
        '--cmd[Command to run in debug container]:command:'
        '--cd-into[Change to directory on start]:directory:_files -/'
    )

    local -a backup_args
    backup_args=(
        '--container-path[Path inside the container to back up]:path:'
        '--local-path[Local destination with template variables]:template:'
        '--compress[Compress backup as tar.gz]'
        '*--tar-exclude[Exclude path or pattern from compressed backup (repeatable)]:pattern:'
    )

    # Determine which subcommand is active by scanning words
    local subcmd=""
    local i
    for (( i=2; i < CURRENT; i++ )); do
        case "${words[i]}" in
            debug|backup) subcmd="${words[i]}"; break ;;
        esac
    done

    case "$subcmd" in
        debug)
            _arguments -s \
                '1:subcommand:(debug backup)' \
                $shared_args $debug_args
            ;;
        backup)
            _arguments -s \
                '1:subcommand:(debug backup)' \
                $shared_args $backup_args
            ;;
        *)
            # No subcommand yet — offer subcommands + shared args + debug args (default)
            _arguments -s $shared_args $debug_args \
                '1:command:(debug backup)'
            ;;
    esac
}

_kdebug "$@"
