from typing import Any
from typing import Dict


def recursive_parse(b: Any) -> Dict[str, Any]:
    """Recursively parses a BeancountType into a nested dictionary of models.

    Since a NamedTuple can be represented as a dictionary using the bultin
    _asdict() method, this function attempts to recursively convert a
    BeancountTuple and any children types into a nested dictionary structure.

    Args:
        b: The BeancountType to recursively parse

    Returns:
        A nested dictionary with all parsed models.
    """
    result: Dict[str, Any] = {}
    for key, value in b._asdict().items():
        if hasattr(value, "_asdict"):
            result[key] = recursive_parse(value)
        elif isinstance(value, list) and value:
            if hasattr(value[0], "_asdict"):
                result[key] = [recursive_parse(c) for c in value]
            else:
                result[key] = value
        else:
            result[key] = value

    return result