Clean up a query string for searching.

    Removes unmatched parentheses and joining operators.

    Arguments:
        q (str): Query string to be cleaned

    Returns:
        str: The clean query string.

def _clean_query_string(q):
    """Clean up a query string for searching.

    Removes unmatched parentheses and joining operators.

    Arguments:
        q (str): Query string to be cleaned

    Returns:
        str: The clean query string.
    """
    q = q.replace("()", "").strip()
    if q.endswith("("):
        q = q[:-1].strip()
    # Remove misplaced AND/OR/NOT at end
    if q[-3:] == "AND" or q[-3:] == "NOT":
        q = q[:-3]
    elif q[-2:] == "OR":
        q = q[:-2]

    # Balance parentheses
    while q.count("(") > q.count(")"):
        q += ")"
    while q.count(")") > q.count("("):
        q = "(" + q

    return q.strip()