#!/usr/bin/env python3
#
# SPDX-License-Identifier: MIT
#
# Copyright (C) 2023 Ying-Chun Liu (PaulLiu) <paulliu@debian.org>
#

import re
import sys
import argparse
from pypinyin.contrib.tone_convert import to_tone


def convert_pinyin_u_umlaut(pinyin):
    return pinyin.replace('u:', 'ü')


def convert_pinyin_tone_numbers_to_tone_marks(pinyin):
    return re.sub(r'([A-Za-zü]+[1-5])', lambda m: to_tone(m.group()), pinyin)


def remove_pinyin_tone_numbers(pinyin):
    return re.sub(r'([A-Za-zü]+)[1-5]', r'\1', pinyin)


def remove_pinyin_spaces(pinyin):
    return re.sub(r'[^\w]+', '', pinyin)


def convert_reference_pinyin_tone_numbers_to_tone_marks(definition):
    return re.sub(r'\[([^]]+)\]', lambda m: convert_pinyin_tone_numbers_to_tone_marks(convert_pinyin_u_umlaut(m.group())), definition)


if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument("dictfile", help="Dictionary file.")

    args = parser.parse_args()

    dictfile = args.dictfile

    main_re = re.compile(r"([^ ]+) ([^ ]+) \[([^]]*)\] /(.*)/")
    fi = open(dictfile, "r")

    print("This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License (click https://creativecommons.org/licenses/by-sa/4.0/ for detailed information)")
    print("It more or less means that you are allowed to use this data for both non-commercial and commercial purposes provided that you: mention where you got the data from (attribution) and that in case you improve / add to the data you will share these changes under the same license (share alike).")

    while True:
        line = fi.readline()
        if not line:
            break
        line = line.strip()
        if len(line) > 0 and line[0] == '#':
            continue
        match = main_re.search(line)
        if match is None:
            print(f'Error: line does not match expected CC-CEDICT format: {line}', file=sys.stderr)
            sys.exit(1)

        index_values = []

        definition = match.group(4)
        definitions = definition.split("/")

        hanzi_trad = match.group(1)
        hanzi_simp = match.group(2)

        pinyin_with_tone_numbers = convert_pinyin_u_umlaut(match.group(3))
        pinyin_with_tone_numbers_without_spaces = remove_pinyin_spaces(pinyin_with_tone_numbers)

        pinyin_with_tone_marks = convert_pinyin_tone_numbers_to_tone_marks(pinyin_with_tone_numbers)
        pinyin_with_tone_marks_without_spaces = remove_pinyin_spaces(pinyin_with_tone_marks)

        pinyin_without_tones = remove_pinyin_tone_numbers(pinyin_with_tone_numbers)
        pinyin_without_tones_without_spaces = remove_pinyin_spaces(pinyin_without_tones)

        if hanzi_trad != hanzi_simp:
            hanzi_combined = f'{hanzi_trad}|{hanzi_simp}'
            index_values.append(hanzi_simp)
            index_values.append(hanzi_trad)
        else:
            hanzi_combined = hanzi_simp
            index_values.append(hanzi_simp)

        index_values.append(pinyin_with_tone_numbers)
        index_values.append(pinyin_with_tone_numbers_without_spaces)
        index_values.append(pinyin_with_tone_marks)
        index_values.append(pinyin_with_tone_marks_without_spaces)
        index_values.append(pinyin_without_tones)
        index_values.append(pinyin_without_tones_without_spaces)

        headword = f'{"%%%".join(sorted(set(index_values)))}^^^{hanzi_combined}'

        print(headword)
        print(f' {hanzi_combined}')
        print(f' [{pinyin_with_tone_marks}]')

        for definition in definitions:
            print(f' {convert_reference_pinyin_tone_numbers_to_tone_marks(definition)}')
