import json
import os


def load_translation_dict(folder):
    with open(os.path.join(folder, "en.json"), "r", encoding="utf-8") as f:
        en_data = json.load(f)

    with open(os.path.join(folder, "zh_CN.json"), "r", encoding="utf-8") as f:
        zh_data = json.load(f)

    translation_dict = {}
    for key, en_value in en_data.items():
        zh_value = zh_data.get(key, "")
        translation_dict[en_value] = zh_value
    return en_data, translation_dict


def replace_ch2_translations(ch1_dict, ch2_en_map, ch2_dict):
    new_zh_data = {}
    for key, en_value in ch2_en_map.items():
        # 如果 ch1 中有相同英文，则替换翻译
        if en_value in ch1_dict and ch1_dict[en_value] != "":
            new_zh_data[key] = ch1_dict[en_value]
        else:
            new_zh_data[key] = ch2_dict.get(en_value, "")
    return new_zh_data


def main():
    ch1_en_map, ch1_dict = load_translation_dict("text_original/ch1")
    ch2_en_map, ch2_dict = load_translation_dict("text_original/ch2")

    new_zh = replace_ch2_translations(ch1_dict, ch2_en_map, ch2_dict)

    with open(
        os.path.join("text_original/ch1", "zh_CN_new.json"), "w", encoding="utf-8"
    ) as f:
        json.dump(new_zh, f, ensure_ascii=False, indent=4)

    print("ch2/zh_CN.json 已成功更新！")


if __name__ == "__main__":
    main()
