#!/usr/bin/env python3

import codecs
import os
import os.path
import shutil
import subprocess
import logging
import glob
import json

CONTEST_DIR = 'polygon-contest'
INIT_FILE = 'init.txt'
BUILD_DIR = 'build'
LANGUAGE = 'russian'
FILES_DIR = 'files-' + LANGUAGE


def time_limit_from_int(tl):
    tl //= 1000
    return str(tl) + ' секунд' + ('a' if tl == 1 else 'ы')

def memory_limit_from_int(ml):
    return str(ml // (1024 ** 2)) + ' мегабайт'

def build_with_text(text, replace_data, result, section='', problem_name=''):
    text = text.replace('%TEXT%', section + '\n' + replace_data)

    with codecs.open(os.path.join(BUILD_DIR, 'data.tex'), 'w', 'utf-8') as data_file:
        data_file.write(text)

    cwd = os.getcwd()
    os.chdir(BUILD_DIR)
    logging.info('Compile problem %s' % problem_name)
    for _ in range(2):
        subprocess.check_output(['pdflatex', 'compile.tex'])
    os.chdir(cwd)

    shutil.copy(os.path.join(BUILD_DIR, 'compile.pdf'), os.path.join(FILES_DIR, result))


def main():
    id_by_name = {}
    with open(INIT_FILE, 'r', encoding='utf-8') as init:
        for line in init:
            if not line.strip():
                continue
            line = line.strip().split('\t')
            id_by_name[line[11]] = line[2]
    logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(levelname)s] %(message)s')
    if not os.path.exists(FILES_DIR):
        logging.info('Create folder for output files: %s' % FILES_DIR)
        os.mkdir(FILES_DIR)
    if not os.path.exists(BUILD_DIR):
        logging.info('Create folder for build files: %s' % BUILD_DIR)
        os.mkdir(BUILD_DIR)

    problems_dir = os.path.join(CONTEST_DIR, 'problems')
    for problem_counter, problem_dir in enumerate(glob.glob(os.path.join(problems_dir, '*')), start=1):
        statement_dir = os.path.join(problem_dir, 'statements', LANGUAGE)
        properties_file_name = os.path.join(statement_dir, 'problem-properties.json')
        logging.info('Read problem properties file %s' % properties_file_name)

        with codecs.open(properties_file_name, 'r', 'utf-8') as properties_file:
            properties = json.load(properties_file)

            name = properties['name']
            legend = properties['legend']
            input_file = properties['inputFile']
            output_file = properties['outputFile']
            time_limit = time_limit_from_int(properties['timeLimit'])
            memory_limit = memory_limit_from_int(properties['memoryLimit'])
            input_format = properties['input']
            output_format = properties['output']
            samples = "".join(["\exmp{%s}{%s}%%\n" % (sample['input'], sample['output'])
                            for sample in properties['sampleTests']])
            notes = ''
            if len(properties.get('notes','')) > 0:
                notes = '\\Note\n' + properties['notes']



            shutil.copy('template.tex', os.path.join(BUILD_DIR, 'compile.tex'))
            shutil.copy('olymp.sty', os.path.join(BUILD_DIR, 'olymp.sty'))
            with codecs.open('data.tex', 'r', 'utf-8') as data_file:
                data = data_file.read()

            problem_name = os.path.basename(problem_dir)
            problem_id = id_by_name[problem_name]
            data = data.replace('%NAME%', name).replace('%INPUT_FILE%', input_file).replace('%OUTPUT_FILE%', output_file).\
                        replace('%TIME_LIMIT%', time_limit).replace('%MEMORY_LIMIT%', memory_limit).\
                        replace('%ID%', problem_id).\
                        replace('%PROBLEM_COUNTER%', str(problem_counter)).\
                        replace('%STATEMENT_DIR%', os.path.join('..', statement_dir).replace('\\', '/') + '/')

            build_with_text(data, legend + '\n\\InputFile\n' + input_format + '\n\\OutputFile\n' + output_format +
                "\\begin{example}" + samples +"\\end{example}\n" + notes,
                problem_name + '.pdf', problem_name=problem_name)


if __name__ == '__main__':
    main()

[(32, 'os.getcwd', 'os.getcwd', False, 'import os\n'), (33, 'os.chdir', 'os.chdir', False, 'import os\n'), (34, 'logging.info', 'logging.info', False, 'import logging\n'), (37, 'os.chdir', 'os.chdir', False, 'import os\n'), (50, 'logging.basicConfig', 'logging.basicConfig', False, 'import logging\n'), (58, 'os.path.join', 'os.path.join', False, 'import os\n'), (36, 'subprocess.check_output', 'subprocess.check_output', False, 'import subprocess\n'), (39, 'os.path.join', 'os.path.join', False, 'import os\n'), (39, 'os.path.join', 'os.path.join', False, 'import os\n'), (51, 'os.path.exists', 'os.path.exists', False, 'import os\n'), (52, 'logging.info', 'logging.info', False, 'import logging\n'), (53, 'os.mkdir', 'os.mkdir', False, 'import os\n'), (54, 'os.path.exists', 'os.path.exists', False, 'import os\n'), (55, 'logging.info', 'logging.info', False, 'import logging\n'), (56, 'os.mkdir', 'os.mkdir', False, 'import os\n'), (60, 'os.path.join', 'os.path.join', False, 'import os\n'), (61, 'os.path.join', 'os.path.join', False, 'import os\n'), (62, 'logging.info', 'logging.info', False, 'import logging\n'), (29, 'os.path.join', 'os.path.join', False, 'import os\n'), (59, 'os.path.join', 'os.path.join', False, 'import os\n'), (64, 'codecs.open', 'codecs.open', False, 'import codecs\n'), (65, 'json.load', 'json.load', False, 'import json\n'), (88, 'os.path.basename', 'os.path.basename', False, 'import os\n'), (83, 'os.path.join', 'os.path.join', False, 'import os\n'), (84, 'os.path.join', 'os.path.join', False, 'import os\n'), (85, 'codecs.open', 'codecs.open', False, 'import codecs\n'), (94, 'os.path.join', 'os.path.join', False, 'import os\n')]