import itertools


def check_length(seed, random, query_words, key_max):
    """
    Google limits searches to 32 words, so we need to make sure we won't be generating anything longer
    Need to consider
    - number of words in seed
    - number of words in random phrase
    - number of words in the lists from the query
    Will raise exception if there are too many words

    Args:
        seed: the seed for segment 1
        random: the random query string for segment 0
        query_words: object with key=name of dimension, value=list of keywords to use in query
        key_max: the maximum number of words (32 in Google's case)

    Returns:
        bool: True for correct number of words, False for too many

    """
    all_query_words = " ".join(list(itertools.chain.from_iterable(query_words))).split(' ')
    total_words = len(seed.split(" ")) + len(random.split(" ")) + len(all_query_words)

    if total_words <= key_max:
        return True
    else:
        message = "The maximum number of keywords is:", key_max, "\nYou have:", total_words
        raise Exception(message)