from typing import Dict


def calc_post_depths_from_thread_structure(thread_structure: Dict) \
        -> Dict[str, int]:
    """Calculates the nested depth of each post in a thread.

    We determine post depth from the provided `structure.json` files in the
    dataset because this is easier than following the chain of a post's
    parents to the source post of a thread.

    Args:
        thread_structure: The parsed JSON dict from one of the dataset's
            `structure.json` files.

    Returns:
        A dictionary mapping post IDs to their nested depth. The source
        post of a thread always has depth `0`, first level replies `1`, etc.

    Example:
        If the `thread_structure` would look like the following::

            {
                'foo': {
                    'bar': [],
                    'baz': {
                        'boogy': []
                    },
                    'qux': []
                }
            }

        The parsed post depths would be::

            {
                'foo': 0,
                'bar': 1,
                'baz': 1,
                'boogy': 2,
                'qux': 1
            }
    """
    post_depths = {}

    def walk(thread: Dict, depth: int) -> None:
        for post_id, subthread in thread.items():
            post_depths[post_id] = depth
            if isinstance(subthread, Dict):
                walk(subthread, depth + 1)

    walk(thread_structure, 0)
    return post_depths