#!/bin/bash

_dasel() {
    local cur prev words cword
    _init_completion || return

    local commands="query version interactive completion man"
    local formats="csv dasel hcl ini json toml xml yaml"
    local shells="bash zsh fish powershell"

    # Find if a subcommand has been specified
    local cmd=""
    for ((i=1; i < cword; i++)); do
        case "${words[i]}" in
            query|version|interactive|completion|man)
                cmd="${words[i]}"
                break
                ;;
        esac
    done

    # Complete format names for --in/--out/-i/-o
    case "${prev}" in
        --in|--out|-i|-o)
            COMPREPLY=($(compgen -W "${formats}" -- "${cur}"))
            return
            ;;
    esac

    if [[ "${cur}" == -* ]]; then
        local flags=""
        case "${cmd}" in
            "")
                # No subcommand yet: offer global flags + query flags (default command)
                flags="--help --var --rw-flag --read-flag --write-flag --in -i --out -o --root --compact --unstable --it --config -c "
                ;;
            query)
                flags="--help --var --rw-flag --read-flag --write-flag --in -i --out -o --root --compact --unstable --it --config -c "
                ;;
            version)
                flags="--help "
                ;;
            interactive)
                flags="--help --var --rw-flag --read-flag --write-flag --in -i --out -o --config -c "
                ;;
            completion)
                flags="--help "
                ;;
            man)
                flags="--help "
                ;;
        esac
        COMPREPLY=($(compgen -W "${flags}" -- "${cur}"))
        return
    fi

    # If no subcommand yet, complete with subcommand names
    if [[ -z "${cmd}" ]]; then
        COMPREPLY=($(compgen -W "${commands}" -- "${cur}"))
    fi
}

complete -F _dasel dasel
