#!/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, 10, 32, 21), 'os.getcwd', 'os.getcwd', ({}, {}), '()', False, 'import os\n'), ((33, 4, 33, 23), 'os.chdir', 'os.chdir', ({(33, 13, 33, 22): 'BUILD_DIR'}, {}), '(BUILD_DIR)', False, 'import os\n'), ((34, 4, 34, 53), 'logging.info', 'logging.info', ({(34, 17, 34, 52): "('Compile problem %s' % problem_name)"}, {}), "('Compile problem %s' % problem_name)", False, 'import logging\n'), ((37, 4, 37, 17), 'os.chdir', 'os.chdir', ({(37, 13, 37, 16): 'cwd'}, {}), '(cwd)', False, 'import os\n'), ((50, 4, 50, 94), 'logging.basicConfig', 'logging.basicConfig', (), '', False, 'import logging\n'), ((58, 19, 58, 56), 'os.path.join', 'os.path.join', ({(58, 32, 58, 43): 'CONTEST_DIR', (58, 45, 58, 55): '"""problems"""'}, {}), "(CONTEST_DIR, 'problems')", False, 'import os\n'), ((36, 8, 36, 60), 'subprocess.check_output', 'subprocess.check_output', ({(36, 32, 36, 59): "['pdflatex', 'compile.tex']"}, {}), "(['pdflatex', 'compile.tex'])", False, 'import subprocess\n'), ((39, 16, 39, 54), 'os.path.join', 'os.path.join', ({(39, 29, 39, 38): 'BUILD_DIR', (39, 40, 39, 53): '"""compile.pdf"""'}, {}), "(BUILD_DIR, 'compile.pdf')", False, 'import os\n'), ((39, 56, 39, 87), 'os.path.join', 'os.path.join', ({(39, 69, 39, 78): 'FILES_DIR', (39, 80, 39, 86): 'result'}, {}), '(FILES_DIR, result)', False, 'import os\n'), ((51, 11, 51, 36), 'os.path.exists', 'os.path.exists', ({(51, 26, 51, 35): 'FILES_DIR'}, {}), '(FILES_DIR)', False, 'import os\n'), ((52, 8, 52, 70), 'logging.info', 'logging.info', ({(52, 21, 52, 69): "('Create folder for output files: %s' % FILES_DIR)"}, {}), "('Create folder for output files: %s' % FILES_DIR)", False, 'import logging\n'), ((53, 8, 53, 27), 'os.mkdir', 'os.mkdir', ({(53, 17, 53, 26): 'FILES_DIR'}, {}), '(FILES_DIR)', False, 'import os\n'), ((54, 11, 54, 36), 'os.path.exists', 'os.path.exists', ({(54, 26, 54, 35): 'BUILD_DIR'}, {}), '(BUILD_DIR)', False, 'import os\n'), ((55, 8, 55, 69), 'logging.info', 'logging.info', ({(55, 21, 55, 68): "('Create folder for build files: %s' % BUILD_DIR)"}, {}), "('Create folder for build files: %s' % BUILD_DIR)", False, 'import logging\n'), ((56, 8, 56, 27), 'os.mkdir', 'os.mkdir', ({(56, 17, 56, 26): 'BUILD_DIR'}, {}), '(BUILD_DIR)', False, 'import os\n'), ((60, 24, 60, 73), 'os.path.join', 'os.path.join', ({(60, 37, 60, 48): 'problem_dir', (60, 50, 60, 62): '"""statements"""', (60, 64, 60, 72): 'LANGUAGE'}, {}), "(problem_dir, 'statements', LANGUAGE)", False, 'import os\n'), ((61, 31, 61, 85), 'os.path.join', 'os.path.join', ({(61, 44, 61, 57): 'statement_dir', (61, 59, 61, 84): '"""problem-properties.json"""'}, {}), "(statement_dir, 'problem-properties.json')", False, 'import os\n'), ((62, 8, 62, 78), 'logging.info', 'logging.info', ({(62, 21, 62, 77): "('Read problem properties file %s' % properties_file_name)"}, {}), "('Read problem properties file %s' % properties_file_name)", False, 'import logging\n'), ((29, 21, 29, 56), 'os.path.join', 'os.path.join', ({(29, 34, 29, 43): 'BUILD_DIR', (29, 45, 29, 55): '"""data.tex"""'}, {}), "(BUILD_DIR, 'data.tex')", False, 'import os\n'), ((59, 60, 59, 91), 'os.path.join', 'os.path.join', ({(59, 73, 59, 85): 'problems_dir', (59, 87, 59, 90): '"""*"""'}, {}), "(problems_dir, '*')", False, 'import os\n'), ((64, 13, 64, 60), 'codecs.open', 'codecs.open', ({(64, 25, 64, 45): 'properties_file_name', (64, 47, 64, 50): '"""r"""', (64, 52, 64, 59): '"""utf-8"""'}, {}), "(properties_file_name, 'r', 'utf-8')", False, 'import codecs\n'), ((65, 25, 65, 51), 'json.load', 'json.load', ({(65, 35, 65, 50): 'properties_file'}, {}), '(properties_file)', False, 'import json\n'), ((88, 27, 88, 56), 'os.path.basename', 'os.path.basename', ({(88, 44, 88, 55): 'problem_dir'}, {}), '(problem_dir)', False, 'import os\n'), ((83, 40, 83, 78), 'os.path.join', 'os.path.join', ({(83, 53, 83, 62): 'BUILD_DIR', (83, 64, 83, 77): '"""compile.tex"""'}, {}), "(BUILD_DIR, 'compile.tex')", False, 'import os\n'), ((84, 37, 84, 73), 'os.path.join', 'os.path.join', ({(84, 50, 84, 59): 'BUILD_DIR', (84, 61, 84, 72): '"""olymp.sty"""'}, {}), "(BUILD_DIR, 'olymp.sty')", False, 'import os\n'), ((85, 17, 85, 54), 'codecs.open', 'codecs.open', ({(85, 29, 85, 39): '"""data.tex"""', (85, 41, 85, 44): '"""r"""', (85, 46, 85, 53): '"""utf-8"""'}, {}), "('data.tex', 'r', 'utf-8')", False, 'import codecs\n'), ((94, 51, 94, 84), 'os.path.join', 'os.path.join', ({(94, 64, 94, 68): '""".."""', (94, 70, 94, 83): 'statement_dir'}, {}), "('..', statement_dir)", False, 'import os\n')]