#!/usr/bin/env python
#encoding: utf8

import sys
import requests
import json
import yaml
import itertools
from collections import namedtuple
from functools import wraps


def load_from_tanker(project, keyset):
    response = requests.get('https://tanker-api.yandex-team.ru/keysets/json/'
        '?project-id=%s&keyset-id=%s&language=ru&status=approved'
        % (project, keyset))
    return json.loads(response.content)['ru']

def memoize(func):
    cache = {}

    @wraps(func)
    def wrapped():
        if not cache.get(()):
            cache[()] = func()
        return cache[()]

    return wrapped

@memoize
def get_longtask_texts():
    return load_from_tanker('nmaps', 'diffalert')

@memoize
def get_editor_texts():
    return load_from_tanker('nmaps', 'task-alerts')


CategoryGroup = namedtuple('CategoryGroup', 'name messages')
Message = namedtuple('Message', 'domain priority description comment editor_text longtask_text')

def load_files(files):
    res = []
    for file in files:
        data = yaml.load(file, Loader=yaml.FullLoader)
        messages = []
        for doc in data['messages']:
            doc['priority'] = tuple(int(p) for p in doc['priority'].split('.'))
            doc.setdefault('comment', '')
            doc.setdefault('domain', 'common')
            doc['longtask_text'] = get_longtask_texts().get('message-' + doc['description'])
            doc['editor_text'] = get_editor_texts().get(doc['description'])
            messages.append(Message(**doc))
        res.append(CategoryGroup(data['category_group'], messages))
    return res


def gen_wiki_docs(category_group, messages):
    check_tanker_keys(messages)

    result = u'==' + category_group + '\n'

    messages.sort(key=lambda m: m.priority)
    for maj_priority, messages in itertools.groupby(messages, lambda m: m.priority[0]):
        result += u'===Приоритет %s\n' % (maj_priority,)
        for m in messages:
            result += u'**({priority[0]}.{priority[1]})** ##{text}##'\
                      .format(priority=m.priority,
                              text=m.longtask_text or m.editor_text)
            if m.domain == 'common' and m.editor_text != m.longtask_text:
                result += u' (в задачах модерации: ##' + m.editor_text + '##)\n'
            else:
                result += u'\n'

            if m.domain == 'editor':
                result += u'Признак только для задач модерации. '
            elif m.domain == 'longtask':
                result += u'Признак только для длинной задачи. '

            result += m.comment

            result = result.rstrip() + '\n\n'

    return result

def check_tanker_keys(messages):
    not_in_editor = [m.description for m in messages
                    if m.domain in ('common', 'editor')
                    and m.description not in get_editor_texts()]
    not_in_longtask = [m.description for m in messages
                       if m.domain in ('common', 'longtask')
                       and 'message-' + m.description not in get_longtask_texts()]
    if not_in_editor or not_in_longtask:
        raise Exception('some keys are not in tanker: editor: %s, longtask: %s'
                        % (not_in_editor, not_in_longtask))


if __name__ == '__main__':
    filenames = sys.argv[1:]
    if len(filenames) == 0 or filenames[0] in ['-h', '--help']:
        print('Usage: %s [doc_file]...' % sys.argv[0])
        exit(0)

    for cat_group in load_files([open(f) for f in filenames]):
        print(gen_wiki_docs(cat_group.name, cat_group.messages))
