import os, shutil, json
from datetime import datetime


# 自动撰写更新日志
def update_changelog(changelog):
    current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    with open("buildnumber.txt", "r+") as f:
        version = int(f.read())
        f.seek(0)
        f.write(str(version + 1))

    # 将时间和版本号写入changelog.md
    with open("changelog.md", "r+") as f:
        f.seek(0, 2)  # 移动到文件末尾
        f.write(f"## 版本号: V{version}\n\n > 构建时间:{current_time}\n\n")
        for key, value in changelog.items():
            f.write(f"### {key} 更新内容:\n\n{value}\n\n")


# 更新历史记录的7z文件并打包
def update_history7z(process):
    # 使用7z命令行工具解压history.7z到临时文件夹
    with open("buildnumber.txt", "r+") as f:
        version = int(f.read())
    for key in process:
        if not os.path.exists(f"{key}/history.7z"):
            os.system(f"cd {key} && 7z a history.7z original.{key.split('-')[1]}")
        os.system(f"7z x {key}/history.7z -otmp/{key}")
        os.remove(f"{key}/history.7z")
        # 将latest.dll/assets重命名为{VERSION}.dll/assets
        shutil.copy(
            f"{key}/latest.{key.split('-')[1]}",
            f"tmp/{key}/V{version}.{key.split('-')[1]}",
        )
        # 重新压缩
        os.system(f"cd tmp/{key} && 7z a ../../{key}/history.7z *")
        # 删除临时文件夹
        shutil.rmtree(f"tmp/{key}")

    if "assembly-dll" in process:
        # 强制复制
        shutil.copy(
            "assembly-dll/latest.dll",
            "translation-tools/gamedata/Managed/Assembly-CSharp.dll",
        )
    if "shaderassets0-assets" in process:
        # 强制复制
        shutil.copy(
            "shaderassets0-assets/latest.assets",
            "translation-tools/gamedata/sharedassets0.assets",
        )


# 将翻译导入回text
def import_translation(
    srcfolder, distfolder, textkeylist, translationsrc, translationdst
):
    # 备份text到text-bk-version
    with open("buildnumber.txt", "r+") as f:
        version = int(f.read())
    if os.path.exists(srcfolder):
        shutil.copytree(srcfolder, distfolder, dirs_exist_ok=True)

    # 将翻译导入text,首先打开对应的json文件
    with open(translationsrc, "r") as f:
        src = json.load(f)
    with open(translationdst, "r") as f:
        dst = json.load(f)

    # 根据 src / dst 构建翻译字典
    transdict = dict()
    for key, item in src.items():
        if key in dst and dst[key] != "":
            transdict[item] = dst[key]
        else:
            transdict[item] = item

    # 遍历distfolder所有的json文件,使用递归来搜索对应的key
    # 遍历目录中的所有文件和子目录
    for root, dirs, files in os.walk(distfolder):
        for file in files:
            if file.endswith(".json"):
                file_path = os.path.join(root, file)
                # 读取每个json文件
                # 读取 json 文件
                with open(file_path, "r", encoding="utf-8") as f:
                    data = json.load(f)
                    # 对每个指定的 key 进行递归搜索并修改
                    for key in textkeylist:

                        def recursive_search(obj):
                            if isinstance(obj, dict):
                                for k, v in obj.items():
                                    if k == key:
                                        # 如果是字符串且存在于 transdict 中,直接修改
                                        if isinstance(v, str) and v in transdict:
                                            obj[k] = transdict[v]
                                        # 如果是列表,逐项检查
                                        elif isinstance(v, list):
                                            for idx, item in enumerate(v):
                                                if (
                                                    isinstance(item, str)
                                                    and item in transdict
                                                ):
                                                    obj[k][idx] = transdict[item]
                                                else:
                                                    recursive_search(item)
                                    else:
                                        recursive_search(v)
                            elif isinstance(obj, list):
                                for item in obj:
                                    recursive_search(item)

                        recursive_search(data)
                    with open(file_path, "w", encoding="utf-8") as f:
                        json.dump(data, f, ensure_ascii=False, indent=2)


if __name__ == "__main__":
    changelog = {
        "assembly-dll": """无""",
        "shaderassets0-assets": """【成功导入字体】DTM-Mono,用于主菜单和正文文本。""",
        "code-csharp": """无""",
        "images-l10n": """无""",
        "rules": """无""",
        "text": """导入mText和TextMeshpro文本!""",
    }
    # update_changelog(changelog)
    # import_translation(
    #     "text",
    #     "text-cn",
    #     ["Text", "Array"],
    #     "translation-tools/weblate/textmeshpro/en.json",
    #     "translation-tools/weblate/textmeshpro/zh_CN.json",
    # )

    import_translation(
        "text",
        "text-cn",
        [
            "m_text",
            "BIOSText",
            "SettingsElementName",
            "SettingsDescription",
            "ExtraName",
            "CreditNames",
            "CreditDescription",
            # 0304补充
            "GoalHint",
            "HypothesisName",
            "HypothesisTagline",
            "HypothesisDescription",
            "TimeWhenWritten",
        ],
        "translation-tools/weblate/mtext/en.json",
        "translation-tools/weblate/mtext/zh_CN.json",
    )
    # update_history7z(["sharedassets0-assets", "assembly-dll"])