from typing import Dict
from typing import List
import random


def generate_chain(model: Dict[str, List[str]], length: int, order: int) -> str:
    """Build a Markov chain from the given model.

    Args:
        model: A dictionary mapping ngrams to possible following words.
        length: The length of the markov chains to generate.
        order: The order of the markov model in use.

    Returns:
        A sentence string markov chain.
    """
    current_ngram = random.choice((list(model)))
    chain = current_ngram.split(" ")

    while len(chain) < length:
        possibilities = model.get(current_ngram)

        if not possibilities:
            break

        next_word = random.choice(possibilities)
        chain.append(next_word)
        current_ngram = " ".join(chain[(-1 * order) :])

    return " ".join(chain)