"""Convert a Jupyter notebook to Python source in Sphinx Gallery format.

How to use:

    $ pip install m2r
    $ cat tutorial.ipynb | python to_python.py > tutorial.py

That will do the bulk of the conversion for you.
Stuff that you'll need to change yourself:

* Replace the placeholder with a unique RST label,
* Replace the placeholder with a decent tutorial title, and
* Little tweaks to make Sphinx happy.

YMMV ;)

"""

import json
import sys

import m2r


def write_docstring(fout):
    fout.write('''r"""
Autogenerated docstring
=======================

Please replace me.

"""
''')


def process_markdown(source, fout):
    def gen():
        for markdown_line in source:
            rst_lines = m2r.convert(markdown_line).split('\n')
            skip_flag = True
            for line in rst_lines:
                if line == '' and skip_flag and False:
                    #
                    # Suppress empty lines at the start of each section, they
                    # are not needed.
                    #
                    continue
                yield line
                skip_flag = bool(line)

    for line in gen():
        fout.write('# %s\n' % line)


def output_cell(cell, fout):
    if cell['cell_type'] == 'code':
        for line in cell['source']:
            fout.write(line.replace('%time ', ''))
    elif cell['cell_type'] == 'markdown':
        fout.write('#' * 79 + '\n')
        process_markdown(cell['source'], fout)
    fout.write('\n\n')


def main():
    write_docstring(sys.stdout)
    notebook = json.load(sys.stdin)
    for cell in notebook['cells']:
        output_cell(cell, sys.stdout)


if __name__ == '__main__':
    main()
