#!/usr/bin/env python3
#
# Call with a recorded asciinema asciicast (v2 only) to get an RST formated
# file with code markup on stdout.

import fileinput
import json
import os
import re

# need the raw truth
os.environ['GIT_PAGER'] = 'cat'

is_comment = re.compile(r'.* % #(\s|)')

cur_line = ''
in_code = False

print("""\
.. The content of this file was auto-generated by your mad uncle from Germany
   using the cast2rst script and a recorded asciicast as input.

   Do not edit this file!

""")

for in_line in fileinput.input():
    obj = json.loads(in_line)
    if isinstance(obj, dict):
        continue
    text = obj[2]
    # weired special cases
    if text == '\x1b[A\r\n':
        text = '\n'
    if text.endswith(' \r'):
        text = text[:-2]
    cur_line += text
    if text.endswith('\n'):
        comment_prefix = is_comment.match(cur_line)
        cur_line = re.sub(r'\r\n', '\n', cur_line)
        if comment_prefix:
            if in_code:
                print('\n', end='')
            in_code = False
            doc = is_comment.sub('', cur_line).rstrip(' ')
            if doc:
                print(doc, end='')
            else:
                print('\n', end='')

        else:
            if not in_code:
                print('\n.. code-block:: ansi-color\n\n', end='')
            in_code = True
            # deal with progress bars and such, that repeatedly overwrite the same line
            code = cur_line
            code = re.sub(r'(\n|^).*\r([^\n])', r'\2', cur_line)
            # indent
            code = re.sub(r'\n', '\n   ', code)
            code = '   ' + code.rstrip(' ')
            print(code, end='')
        cur_line=''
