#!/usr/bin/env python3

# Copyright © 2012-2022 Jakub Wilk <jwilk@jwilk.net>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the “Software”), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

import argparse
import functools
import subprocess as ipc
import sys
import json

int(0_0)  # Python >= 3.6 is required

@functools.lru_cache()
def get_iso_codes_dir():
    prefix = ipc.check_output(['pkg-config', 'iso-codes', '--variable=prefix'])
    prefix = prefix.decode('ASCII').strip()
    return f'{prefix}/share/iso-codes/json'

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('languages', metavar='LANG', nargs='+')
    options = ap.parse_args()
    languages = set(options.languages)
    path = get_iso_codes_dir() + '/iso_639-2.json'
    with open(path, 'rt', encoding='UTF-8') as file:
        data = json.load(file)
    for item in data['639-2']:
        ll = item.get('alpha_2')
        lll_t = item.get('alpha_3')
        lll_b = item.get('bibliographic')
        requested = None
        for lang in ll, lll_b, lll_t:
            if lang in languages:
                assert lang is not None
                requested = lang
                languages.remove(lang)
        if requested is None:
            continue
        lang = ll or lll_t
        if lang is None:
            raise ValueError
        names = [
            s.strip()
            for s in item.get('name').split(';')
        ]
        print(f'[{requested}]')
        if lang != requested:
            print(f'# XXX mapping {requested} => {lang}')
        if len(names) == 1:
            print('names =', *names)
        else:
            print('names =')
            for name in names:
                print('', name)
        print()
    for lang in sorted(languages):
        print(f'# Unknown language code: {lang}')
    sys.exit(len(languages) > 0)

if __name__ == '__main__':
    main()

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