#!/usr/bin/env python3

import sys

def split_sections(src):
    ret = []
    start_section = False
    section = ""
    for line in src.split("\n"):
        if start_section:
            if line == "":
                continue
            else:
                start_section = False
        if line.startswith("#"):
            if section != "":
                while section.endswith("\n"):
                    section = section[:-1]
                ret.append(section)
                section = ""
            start_section = True
        section += line + "\n"
    if section != "":
        ret.append(section)
    return ret

def split_blocks(src):
    return src.split("\n\n\n")

def convert_block_to_prt(blk):
    ret = ""

    lines = blk.split("\n")

    prev_nl = True
    for line in lines:
        if ret != "":
            if line == "":
                ret += "\n\n"
                prev_nl = True
            else:
                if line.startswith("「") and line.endswith("」"):
                    ret += "  \n"
                elif not prev_nl:
                    ret += "  \n"
                prev_nl = False
        ret += line
        if line.startswith("#"):
            ret += "\n"
    return ret

def convert_block_to_pub(blk):
    ret = ""

    first = True

    lines = blk.split("\n")
    for line in lines:
        if line.startswith("「") and line.endswith("」"):
            first = False
            if ret != "":
                ret += "\n"
        elif line.startswith("#"):
            pass
        elif first:
            first = False
            ret += "\n　"
        elif line == "":
            first = True
        ret += line
    return ret

def convert(src):
    sections = split_sections(src)
    prt = ""
    pub = ""
    first = True
    for sect in sections:
        blocks = split_blocks(sect)
        prt_blocks = [convert_block_to_prt(blk) for blk in blocks]
        pub_blocks = [convert_block_to_pub(blk) for blk in blocks]
        if first:
            first = False
        else:
            prt += "\n\n"
            pub += "\n\n"
        prt += "\n\n".join(prt_blocks)
        pub += "\n\n<p><br /></p>\n\n".join(pub_blocks)
    return (prt, pub)

def main(input_file, output_name):
    f = open(input_file)
    src = f.read()
    (prt, pub) = convert(src)
    prt_f = open(output_name + "-preview.md", "w")
    prt_f.write(prt)
    pub_f = open(output_name + "-forpub.md", "w")
    pub_f.write(pub)

if __name__ == '__main__':
    if len(sys.argv) != 3 and len(sys.argv) != 2:
        print("args must be 1 (input) or 2 (input, output-name)")
        exit(1)
    if len(sys.argv) == 2:
        name = sys.argv[1].replace(".md", "")
    else:
        name = sys.argv[2]
    main(sys.argv[1], name)
