#!/usr/bin/env python3

# Copyright © 2019 Jakub Wilk <jwilk@jwilk.net>
# SPDX-License-Identifier: MIT

import argparse
import collections
import re

import pycparser.c_parser

names_to_codes = {
    "Alarabia": ['ar'],
    "Alarabia / English": ['ar', 'en'],
    "Alarabia / Français": ['ar', 'fr'],
    "Cesky / Slovencina": ['cs', 'sk'],
    "Deutsch": ['de'],
    "Eesti": ['et'],
    "Ellinika'": ['el'],
    "English": ['en'],
    "Français": ['fr'],
    "Italiano": ['it'],
    "Ivrit": ['he'],
    "Lettish / Lietuviskai": ['lt'],
    "Polski": ['pl'],
    "Português / Español": ['es', 'pt'],
    "Româna": ['ro'],
    "Russky / Balgarski": ['ru', 'bg'],
    "Srbski / Hrvatski / Slovenscina": ['sr', 'hr', 'sl'],
    "Srpski / Hrvatski": ['sr', 'hr'],
    "Svenska / Suomi / Magyar": ['sv', 'fi', 'hu'],
    "Türkçe": ['tr'],
    "Ukrayins'ka": ['uk'],
}

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('path', metavar='/path/to/zvbi/src/lang.c')
    options = ap.parse_args()
    pc = pycparser.c_parser.CParser()
    with open(options.path, 'rt', encoding='ISO-8859-1') as file:
        code = file.read()
    match = re.compile(r'^vbi_font_descriptors\[\d+\]\s*=\s*[{].*?[}];', re.MULTILINE | re.DOTALL).search(code)
    code = 'struct vbi_font_descr ' + match.group()
    code = re.compile('/[*].*?[*]/', re.DOTALL).sub('', code)
    ast = pc.parse(code)
    [decl] = ast.ext
    ilist = decl.init
    data = collections.defaultdict(list)
    for n, elt in enumerate(ilist.exprs):
        [g0, _, _, names] = elt.exprs
        if names.type == 'int':
            continue
        names = names.value.strip('" ')
        codes = names_to_codes[names]
        for code in codes:
            if code in {'sr', 'hr'}:
                if g0.name == 'LATIN_G0':
                    code += '-Latn'
                else:
                    code += '-Cyrl'
            data[code] += [n]
    print('/* Generated automatically by private/gen-region-table. Do not edit. */')
    print()
    print('#include <stddef.h>')
    print()
    print('#include "region-table.h"')
    print()
    print('#define R(n) (1 << (n / 8))')
    print()
    print('const struct langdatum langdata[] = {')
    for code, regions in sorted(data.items()):
        regions = sorted(regions)
        regions = ' | '.join('R({0:04o})'.format(rg) for rg in regions)
        print('    {"', code, '", ', regions, '},', sep='')
    print('    {NULL, -1}')
    print('};')

if __name__ == '__main__':
    main()

# vim:ts=4 sts=4 sw=4 et
