import os
from os import listdir
from subprocess import check_call


def convert_notebook(notebook_path):
    # Generate .py file from a notebook
    notebook_dir, notebook_file_name = os.path.split(notebook_path)
    check_call(
        ['jupyter', 'nbconvert', '--to', 'script', notebook_file_name],
        cwd=notebook_dir,
    )
    py_name = os.path.splitext(notebook_file_name)[0] + ".py"
    full_py_name = os.path.join(notebook_dir, py_name)

    # Create py_gen/ dir if it doesn't exist and move the file there
    new_dir = os.path.join(notebook_dir, 'py_gen')
    if not os.path.exists(new_dir):
        os.makedirs(new_dir)
    new_py_location = os.path.join(new_dir, py_name)
    os.rename(full_py_name, new_py_location)
    full_py_name = new_py_location

    with open(full_py_name, 'r') as f:
        data = f.read()
    lines = data.split('\n')
    good_lines = []
    for line in lines:
        if ("get_ipython().magic" not in line
                and "get_ipython().run_line_magic" not in line):
            good_lines.append(line)
    # Update the file with do not edit preamble
    with open(full_py_name, 'w') as f:
        f.write("#########################################################\n")
        f.write("#\n")
        f.write("# DO NOT EDIT THIS FILE. IT IS GENERATED AUTOMATICALLY. #\n")
        f.write("# PLEASE LOOK INTO THE README FOR MORE INFORMATION.     #\n")
        f.write("#\n")
        f.write("#########################################################\n")
        f.write("\n")

        for line in good_lines:
            f.write(line + '\n')


def main():
    tutorials_folder = os.path.dirname(os.path.realpath(__file__))
    print("tutorials_folder: ", tutorials_folder)
    files = [
        os.path.join(tutorials_folder, f)
        for f in listdir(tutorials_folder)
        if os.path.isfile(os.path.join(tutorials_folder, f))
        and f.endswith('ipynb')
    ]
    for f in files:
        convert_notebook(f)


if __name__ == '__main__':
    main()
