import os
import re
import markdown
import yaml
import shutil
import subprocess
import unidecode
htmltemplate = """
    {title} 
    
{body}"""
settingsfile = "../textes/settings.yml"
def apply_html_template(body, title):
    return htmltemplate.format(body=body, title=title)
def md2html(md):
    return markdown.markdown(md, extensions=['extra', 'nl2br'])
def md2gmi(md):
    gmi = md
    gmi = re.sub(r'\[(.*)\]\((.*)\)', r'\n=> \2 \1', gmi)
    gmi = gmi.replace('* * *', '---')
    gmi = re.sub(r'^\*(.*)\*$', r'> \1', gmi, flags=re.MULTILINE)
    gmi = re.sub(r'\*(.*)\*', r'\1', gmi)
    return gmi
with open(settingsfile, "r", encoding="utf-8") as file:
    index = yaml.safe_load(file)
htmlhome = "{} {}
".format(index['title'], index['description'])
gmihome = "# {}\n{}".format(index['title'], index['description'])
os.makedirs("out/html", exist_ok=True)
os.makedirs("out/gmi", exist_ok=True)
for folderinfo in index['folders']:
    sectiontitle = folderinfo['title']
    htmlhome += "\n{} \n".format(sectiontitle)
    gmihome += "\n\n## {}".format(sectiontitle)
    for fileinfo in folderinfo['files']:
        filetitle = fileinfo['title']
        filename = fileinfo['file']
        fileroot, fileextension = os.path.splitext(filename)
        outfilename = unidecode.unidecode(filename)
        if fileextension == '.md':
            with open(os.path.join(folderinfo['folder'], filename), "r", encoding="utf-8") as mdfile:
                mdcontent = mdfile.read()
            # clean header
            mdcontent = re.sub(r'---\n[\s\S]*?\n---\n*', '', mdcontent)
            htmlcontent = md2html(mdcontent)
            gmicontent = md2gmi(mdcontent)
            with open("out/html/{}".format(outfilename).replace('.md', '.html'), "w", encoding="utf-8") as htmlfile:
                htmlfile.write(apply_html_template(htmlcontent, "{} | {}".format(filetitle, index['title'])))
            with open("out/gmi/{}".format(outfilename).replace('.md', '.gmi'), "w", encoding="utf-8") as gmifile:
                gmifile.write(gmicontent)
            htmlhome += "{} {} {}  "
with open("out/html/index.html", "w", encoding="utf-8") as htmlindex:
    htmlindex.write(apply_html_template(htmlhome, index['title']))
with open("out/gmi/index.gmi", "w", encoding="utf-8") as gmiindex:
    gmiindex.write(gmihome)