#! /usr/bin/env python3

# Copyright © Michal Čihař <michal@weblate.org>
#
# SPDX-License-Identifier: MIT

import csv
import json

names = {}

EXCEPTIONS = {
    "zh": "zh_Hans",
    "sh": "sr_Latn",
    "nb": "nb_NO",
    "no": "nb_NO",
}


def parse_csv(name):
    result = {}
    with open(name) as csvfile:
        reader = csv.reader(csvfile, delimiter=",")
        next(reader)
        for data in reader:
            if data[0] == "#":
                continue
            if data[0] in result:
                raise ValueError(f"Duplicate {data[0]} in {name}!")
            result[data[0]] = data
    return result


def add_name(item):
    if "alpha_2" not in item:
        return
    target = item["alpha_2"]
    if target in EXCEPTIONS:
        target = EXCEPTIONS[target]
    if "alpha_3" in item:
        names[item["alpha_3"]] = target
    if "bibliographic" in item:
        names[item["bibliographic"]] = target


with open("modules/iso-codes/data/iso_639-2.json") as handle:
    for item in json.load(handle)["639-2"]:
        add_name(item)

with open("modules/iso-codes/data/iso_639-3.json") as handle:
    for item in json.load(handle)["639-3"]:
        add_name(item)

aliases = parse_csv("aliases.csv")

lines = []
for name, alias in sorted(names.items()):
    if name not in aliases:
        lines.append(f"{name},{alias}\n")

with open("aliases.csv", "a") as handle:
    handle.writelines(sorted(lines))
