def scope_out(ctx):
    """
    drop last stack item if:
     - we have reach the end of stack
     - and don't wait any input

    :param ctx:
    :return:
    """
    logger.debug('# scope_out')
    logger.debug(ctx)
    # we reach the end of story line
    # so we could collapse previous scope and related stack item
    if ctx.is_tail_of_story() and ctx.could_scope_out():
        logger.debug('# [<] return')
        ctx = ctx.clone()
        ctx.message['session']['stack'] = ctx.message['session']['stack'][:-1]
        if not ctx.is_empty_stack() and \
                (ctx.is_scope_level_part() or \
                         ctx.is_breaking_a_loop()):
            # isinstance(ctx.get_current_story_part(), loop.StoriesLoopNode) and \
            # isinstance(ctx.waiting_for, callable.EndOfStory) or \
            ctx.message = modify_stack_in_message(ctx.message,
                                                  lambda stack: stack[:-1] + [{
                                                      'data': stack[-1]['data'],
                                                      'step': stack[-1]['step'] + 1,
                                                      'topic': stack[-1]['topic'],
                                                  }])
            if ctx.is_breaking_a_loop() and not ctx.is_scope_level():
                ctx.waiting_for = None

        logger.debug(ctx)

    return ctx