from typing import List
from typing import Dict


def join_cumulative_messages(retrieved_data: dict) -> List[dict]:
    """
    Parse cumulative messages by order of created (ascending) and join them together if sequential.

    Parameters
    ----------
    retrieved_data : `dict`
        The contents of the `retrieved.json` file.

    Returns
    -------
    `List[dict]`
        A list of cumulative `dict`s.
    """

    joined_messages: List[dict] = []

    # Combine all of the consecutive messages together.

    cumulative_message: str = ""
    cumulative_attachments: List[Dict[str, str]] = []
    author: str = ""
    last_author: str = ""
    last_seen_date: str = ""

    for message in reversed(retrieved_data["messages"]):
        author = message["author"]["mention_name"]
        attachments: List[Dict[str, str]] = [
            {
                "url": attachment["url"],
                "thumbnail_url": attachment["thumbnail_url"],
            }
            for attachment in message["attachments"]
        ]
        last_seen_date = message["created_at"]

        if author == last_author or not last_author:
            cumulative_message += f"\n{message['content']}\n"
            cumulative_attachments.extend(attachments)
        else:
            joined_messages.append(
                {
                    "message": cumulative_message,
                    "attachments": cumulative_attachments,
                    "author": last_author,
                    "created_at": last_seen_date,
                }
            )

            cumulative_message = message["content"]
            cumulative_attachments = attachments

        last_author = author

    # Write the very last entry.

    if author:
        joined_messages.append(
            {
                "message": cumulative_message,
                "attachments": cumulative_attachments,
                "author": author,
                "created_at": last_seen_date,
            }
        )

    return joined_messages