import re

def pinyinify(pystr):
    c1s = {
            'A': ['Ā', 'Á', 'Ǎ', 'À', 'A'],
            'O': ['Ō', 'Ó', 'Ǒ', 'Ò', 'O'],
            'E': ['Ē', 'É', 'Ě', 'È', 'E'],
            'a': ['ā', 'á', 'ǎ', 'à', 'a'],
            'o': ['ō', 'ó', 'ǒ', 'ò', 'o'],
            'e': ['ē', 'é', 'ě', 'è', 'e'],
            }

    c2s = {
            'i': ['ī', 'í', 'ǐ', 'ì', 'i'],
            'u': ['ū', 'ú', 'ǔ', 'ù', 'u'],
            'ü': ['ǖ', 'ǘ', 'ǚ', 'ǜ', 'ü'],
            }

    rms = {'r5': 'r', 'm2': 'ḿ', 'm4': 'm̀'}

    pys = re.split(r'(?<=[1-5 -])', pystr)
    result = ''
    for pyo in pys:
        py = pyo[:]

        if not py:
            continue

        if py in rms:
            result += rms[py]
            continue

        if py[-1] not in ('1', '2', '3', '4', '5'):
            result += py
            continue

        py = py.replace('u:', 'ü')
        n = int(py[-1]) - 1
        flag = 0

        for c in py[:-1]:
            if c in c1s:
                result += py[:-1].replace(c, c1s[c][n])
                flag = 1
                break

        if flag == 1:
            continue

        for c in reversed(py[:-1]):
            if c in c2s:
                result += py[:-1].replace(c, c2s[c][n])
                flag = 1
                break

        if flag == 1:
            continue

        result += pyo

    return result


css = '<link href="ccced.css" rel="stylesheet">'

with open("cedict_ts.u8", encoding="utf-8-sig", mode="r") as frc:
    for line in frc:
        line = line.strip()

        if not line:
            continue
        if line.startswith("#"):
            continue

        cnhws = list(dict.fromkeys(line.split(" [")[0].split()))
        pinyin = line.split(" [")[1].split("] ")[0].strip("[]")
        endefs = line.split(" /")[1].strip("/").split("/")


        dc = f'<div class="pinyin">{pinyinify(pinyin)}</div>'
        dc += '<div class="headword">'
        dc += ' '.join(cnhws)
        dc += '</div>'
        dc += '<div class="definition">'
        dc += '</div><div class="definition">'.join(endefs)
        dc += '</div>'

        dc = re.sub(r"(?<=\[)([^][]+)(?=\])", lambda m: pinyinify(m.group(1)), dc)

        for cnhw in cnhws:
            cnhw = cnhw.replace('{', '').replace('}', '')
            cnhw = cnhw.strip()
            if not cnhw:
                continue
            with open("dict.txt", encoding="utf-8", mode="a") as fad:
                fad.write(cnhw+"\n"+css+dc+"\n</>\n")
            print(cnhw)
