# Save clap-generated function so we can delegate non-dynamic cases.
functions[_rsp_clap]=$functions[_rsp]

_rsp() {
    case $words[2] in
        play|queue)
            if (( CURRENT > 2 )); then
                _rsp_complete_args
                return 0
            fi
            ;;
    esac
    _rsp_clap "$@"
}

_rsp_complete_args() {
    setopt localoptions
    setopt nobanghist
    local -a args=("${(@)words[3,$CURRENT]}")
    local cur="${(j: :)args}"
    local cur_clean="${cur//\\/}"
    local -a suggestions
    suggestions=("${(@f)"$(rsp db-complete "$cur" 2>/dev/null)"}")
    # Filter out empty entries (e.g. from empty command output)
    local -a filtered=()
    for s in "${suggestions[@]}"; do
        if [[ -n "$s" ]]; then
            filtered+=("$s")
        fi
    done
    suggestions=("${filtered[@]}")
    if (( ${#suggestions} )); then
        local noslash="${cur_clean//\/}"
        local n_slashes=$(( ${#cur_clean} - ${#noslash} ))
        local -a display=()
        local -a vals=()
        for s in "${suggestions[@]}"; do
            vals+=("$s")
            if [[ "$cur_clean" == */ ]]; then
                local stripped="$s"
                local i=0
                while (( i < n_slashes )); do
                    stripped="${stripped#*/}"
                    (( i++ ))
                done
                display+=("$stripped")
            else
                display+=("$s")
            fi
        done
        if (( ${#suggestions} > 1 )); then
            compstate[insert]=menu
        fi
        if [[ ${vals[1]} == */ ]]; then
            compadd -U -S '' -M 'm:{a-z}={A-Z} l:|=*' -d display -- "${vals[@]}"
        else
            compadd -U -M 'm:{a-z}={A-Z} l:|=*' -d display -- "${vals[@]}"
        fi
    else
        compadd -U -S ''
    fi
}
