#!/usr/bin/env python
import os
import sys


class Node:
    indentation = ' ' * 4

    def __init__(self, line: str):
        self.is_output_cell = line.startswith(self.indentation)
        self.text = []
        self.is_python_cell = False

        self.add_text(line)

    def add_text(self, line: str):
        if line.startswith('```'):
            self.is_python_cell = not self.is_python_cell

        if not self.is_python_cell and self.is_output_cell:
            line = line.lstrip(self.indentation)
        self.text.append(line)

    def fmt(self):
        text = ''.join(self.text)

        if self.is_output_cell:

            text = text.rstrip() + '\n{: .remo__output-code }\n'

        return text


def fmt(input_file, output_file):
    print('Apply fmt to', input_file)

    nodes = [Node('')]
    with open(input_file) as in_file:
        for line in in_file:
            if not nodes[-1].is_python_cell and line.startswith(Node.indentation) != nodes[-1].is_output_cell:
                nodes.append(Node(line))
            else:
                nodes[-1].add_text(line)

    with open(output_file, mode='w') as out_file:
        for node in nodes:
            out_file.write(node.fmt())


def file_ext(file_path):
    _, ext = os.path.splitext(file_path)
    return ext


if __name__ == '__main__':
    args = sys.argv[1:]

    if len(args) == 2:
        input_file, output_file = args
        if os.path.isfile(input_file):
            fmt(input_file, output_file)

    elif len(args) == 1:
        path = args[0]
        if os.path.isdir(path):
            files = [os.path.join(path, file_name) for file_name in os.listdir(path)]
            md_files = filter(lambda file_path: file_ext(file_path) == '.md', files)
            for md_file in md_files:
                fmt(md_file, md_file)
