import re


def _format_title_to_movielens_format(original_title):
    """
    The movielens dataset formats titles starting with articles such as
    'A', 'The' or 'Los', and adds double quotes around it.

    (but some movies stay as is, e.g.: The Butterfly Effect 3: Revelations (2009))

    Example Input:
        The Lazarus Project (2008)
        The Cry (Il Grido) (1957)
        A Hell of a Day (Reines d'un jour) (2001)
    Example Output:
        "Lazarus Project, The (2008)"
        "Cry, The (Grido, Il) (1957)"
        "Hell of a Day, A (Reines d'un jour) (2001)"

    :param original_title:
    :return:
    """
    articles = ["The", "A", "An"]

    # e.g.: "The Lazarus Project (2008)"
    pat_no_subtitle = r'^([^\(]+) (\(\d{4}\))$'

    # e.g. "A Hell of a Day (Reines d'un jour) (2001)"
    pat_with_subtitle = r'^([^\(]+) (\([^\(]+\)) (\(\d{4}\))$'

    pat_first_word_w_space = r'^(\w+ )(.+)$'

    for article in articles:
        if original_title.startswith(article):

            # option 1 - no subtitles
            match = re.match(pat_no_subtitle, original_title)

            if match:
                title = match.group(1)
                year = match.group(2)

                first_word_match = re.match(pat_first_word_w_space, title)

                # believe it or not, there is a movie called 'A'
                if first_word_match:
                    first_word = first_word_match.group(1)

                    title_no_article = re.sub(pat_first_word_w_space, r'\2', title)

                    title_article_in_front = title_no_article + ", " + first_word

                    formatted_title = title_article_in_front + year

                    return '"' + formatted_title + '"'

            # option 2 - with subtitles
            match = re.match(pat_with_subtitle, original_title)

            if match:
                main_title = match.group(1)
                subtitle = match.group(2)
                year = match.group(3)

                first_word_match = re.match(pat_first_word_w_space, main_title)

                # believe it or not, there is a movie called 'A'
                if first_word_match:
                    first_word = first_word_match.group(1)

                    main_title_no_article = re.sub(pat_first_word_w_space, r'\2', main_title)

                    main_title_article_in_front = main_title_no_article + ", " + first_word

                    formatted_title = main_title_article_in_front + subtitle + " " + year

                    return '"' + formatted_title + '"'

    # no match, return original
    return original_title