#!/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()

[((721, 732), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (730, 732), False, 'import os\n'), ((737, 756), 'os.chdir', 'os.chdir', (['BUILD_DIR'], {}), '(BUILD_DIR)\n', (745, 756), False, 'import os\n'), ((761, 810), 'logging.info', 'logging.info', (["('Compile problem %s' % problem_name)"], {}), "('Compile problem %s' % problem_name)\n", (773, 810), False, 'import logging\n'), ((899, 912), 'os.chdir', 'os.chdir', (['cwd'], {}), '(cwd)\n', (907, 912), False, 'import os\n'), ((1269, 1364), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.DEBUG', 'format': '"""%(asctime)s [%(levelname)s] %(message)s"""'}), "(level=logging.DEBUG, format=\n    '%(asctime)s [%(levelname)s] %(message)s')\n", (1288, 1364), False, 'import logging\n'), ((1653, 1690), 'os.path.join', 'os.path.join', (['CONTEST_DIR', '"""problems"""'], {}), "(CONTEST_DIR, 'problems')\n", (1665, 1690), False, 'import os\n'), ((842, 894), 'subprocess.check_output', 'subprocess.check_output', (["['pdflatex', 'compile.tex']"], {}), "(['pdflatex', 'compile.tex'])\n", (865, 894), False, 'import subprocess\n'), ((930, 968), 'os.path.join', 'os.path.join', (['BUILD_DIR', '"""compile.pdf"""'], {}), "(BUILD_DIR, 'compile.pdf')\n", (942, 968), False, 'import os\n'), ((970, 1001), 'os.path.join', 'os.path.join', (['FILES_DIR', 'result'], {}), '(FILES_DIR, result)\n', (982, 1001), False, 'import os\n'), ((1371, 1396), 'os.path.exists', 'os.path.exists', (['FILES_DIR'], {}), '(FILES_DIR)\n', (1385, 1396), False, 'import os\n'), ((1406, 1468), 'logging.info', 'logging.info', (["('Create folder for output files: %s' % FILES_DIR)"], {}), "('Create folder for output files: %s' % FILES_DIR)\n", (1418, 1468), False, 'import logging\n'), ((1477, 1496), 'os.mkdir', 'os.mkdir', (['FILES_DIR'], {}), '(FILES_DIR)\n', (1485, 1496), False, 'import os\n'), ((1508, 1533), 'os.path.exists', 'os.path.exists', (['BUILD_DIR'], {}), '(BUILD_DIR)\n', (1522, 1533), False, 'import os\n'), ((1543, 1604), 'logging.info', 'logging.info', (["('Create folder for build files: %s' % BUILD_DIR)"], {}), "('Create folder for build files: %s' % BUILD_DIR)\n", (1555, 1604), False, 'import logging\n'), ((1613, 1632), 'os.mkdir', 'os.mkdir', (['BUILD_DIR'], {}), '(BUILD_DIR)\n', (1621, 1632), False, 'import os\n'), ((1819, 1868), 'os.path.join', 'os.path.join', (['problem_dir', '"""statements"""', 'LANGUAGE'], {}), "(problem_dir, 'statements', LANGUAGE)\n", (1831, 1868), False, 'import os\n'), ((1900, 1954), 'os.path.join', 'os.path.join', (['statement_dir', '"""problem-properties.json"""'], {}), "(statement_dir, 'problem-properties.json')\n", (1912, 1954), False, 'import os\n'), ((1963, 2033), 'logging.info', 'logging.info', (["('Read problem properties file %s' % properties_file_name)"], {}), "('Read problem properties file %s' % properties_file_name)\n", (1975, 2033), False, 'import logging\n'), ((615, 650), 'os.path.join', 'os.path.join', (['BUILD_DIR', '"""data.tex"""'], {}), "(BUILD_DIR, 'data.tex')\n", (627, 650), False, 'import os\n'), ((1751, 1782), 'os.path.join', 'os.path.join', (['problems_dir', '"""*"""'], {}), "(problems_dir, '*')\n", (1763, 1782), False, 'import os\n'), ((2048, 2095), 'codecs.open', 'codecs.open', (['properties_file_name', '"""r"""', '"""utf-8"""'], {}), "(properties_file_name, 'r', 'utf-8')\n", (2059, 2095), False, 'import codecs\n'), ((2141, 2167), 'json.load', 'json.load', (['properties_file'], {}), '(properties_file)\n', (2150, 2167), False, 'import json\n'), ((3177, 3206), 'os.path.basename', 'os.path.basename', (['problem_dir'], {}), '(problem_dir)\n', (3193, 3206), False, 'import os\n'), ((2925, 2963), 'os.path.join', 'os.path.join', (['BUILD_DIR', '"""compile.tex"""'], {}), "(BUILD_DIR, 'compile.tex')\n", (2937, 2963), False, 'import os\n'), ((3002, 3038), 'os.path.join', 'os.path.join', (['BUILD_DIR', '"""olymp.sty"""'], {}), "(BUILD_DIR, 'olymp.sty')\n", (3014, 3038), False, 'import os\n'), ((3057, 3094), 'codecs.open', 'codecs.open', (['"""data.tex"""', '"""r"""', '"""utf-8"""'], {}), "('data.tex', 'r', 'utf-8')\n", (3068, 3094), False, 'import codecs\n'), ((3665, 3698), 'os.path.join', 'os.path.join', (['""".."""', 'statement_dir'], {}), "('..', statement_dir)\n", (3677, 3698), False, 'import os\n')]