#!/usr/bin/env python3
# License: https://unlicense.org/
from os import walk
import re


class Article():

    def __init__(self, file):
        self.title = [file.readline(), file.readline()]
        assert re.search(r'^\w.*$', self.title[0]), self.title
        assert re.search(r'^#+$', self.title[1]), self.title
        self.meta = {}
        for line in file:
            if re.search(r'^\s*$', line):
                break
            else:
                k, v = re.search(r'^(:[^:]+:)(.+)$', line).groups()
                assert k not in self.meta, k
                self.meta[k] = v
        self.body = file.read()

    def __str__(self):
        t = '\n'.join(k+v for k,v in self.meta.items())
        return ''.join(self.title) + t + '\n\n' + self.body


def rewrite_articles():
    for root, dirs, files in walk('content'):
        for name in files:
            if name.endswith('.rst'):
                path = root + '/' + name
                try:
                    with open(path, encoding='utf-8') as f:
                        article = Article(f)
                        yield article
                    with open(path, 'w', encoding='utf-8') as f:
                        f.write(str(article))
                except Exception as e:
                    raise Exception(path) from e


for article in rewrite_articles():
    if ':category:' in article.meta:
        cats = article.meta[':category:'].strip().lower()
        del article.meta[':category:']
        tags = article.meta.get(':tags:')
        if cats != 'uncategorized':
            article.meta[':tags:'] = ' ' + cats + (', ' + tags if tags else '')

    if ':author:' in article.meta:
        del article.meta[':author:']
    if ':attachments:' in article.meta:
        del article.meta[':attachments:']
