import re


def parse_flattened_result(to_parse):
    """
        Parse out the belief state from the raw text.
        Return an empty list if the belief state can't be parsed

        Input:
        - A single <str> of flattened result
          e.g. 'User: Show me something else => Belief State : DA:REQUEST ...'

        Output:
        - Parsed result in a JSON format, where the format is:
            [
                {
                    'act': <str>  # e.g. 'DA:REQUEST',
                    'slots': [
                        <str> slot_name,
                        <str> slot_value
                    ]
                }, ...  # End of a frame
            ]  # End of a dialog
    """
    dialog_act_regex = re.compile('([\w:?.?]*)  *\[([^\]]*)\]')
    slot_regex = re.compile('([A-Za-z0-9_.-:]*)  *= ([^,]*)')

    belief = []

    # Parse
    # to_parse: 'DIALOG_ACT_1 : [ SLOT_NAME = SLOT_VALUE, ... ] ...'
    to_parse = to_parse.strip()

    for dialog_act in dialog_act_regex.finditer(to_parse):
        d = dict()
        d['act'] = dialog_act.group(1).replace('.', ':')
        d['slots'] = []

        for slot in slot_regex.finditer(dialog_act.group(2)):
            d['slots'].append(
                [
                    slot.group(1).strip(),
                    slot.group(2).strip().replace(' ', '')
                ]
            )

        if d != {}:
            belief.append(d)

    return belief