import re


def optimade_filter_conversion(filter_expr):
    """
    Convert optimade filters to oqmdap formationenergy filters
    Input:
        :str : original filter expression
    Output:
        :str : converted filter expression
    """
    filter_expr_out = filter_expr

    # General conversion
    filter_expr_out = filter_expr_out.replace('_oqmd_', '')
    filter_expr_out = filter_expr_out.replace('&', 'AND')
    filter_expr_out = filter_expr_out.replace('|', 'OR')
    # Convert 'elements=' into mutiple 'element=' filters
    for els in re.findall('elements=[^-0-9\/]+', filter_expr):
        els_out = els.replace('elements=', '')

        els_lst = [' element='+e+' ' for e in els_out.split(',')]

        els_out = ' AND '.join(els_lst)

        filter_expr_out = filter_expr_out.replace(els, '('+els_out+')')


    return filter_expr_out