import os, re, sys

log_path = "debug_log.txt"
with open(log_path, "w", encoding="utf-8") as log:
    input_folder = os.getcwd()
    output_folder = os.path.join(input_folder, "output_json")
    os.makedirs(output_folder, exist_ok=True)

    log.write(f"当前目录: {input_folder}\n\n")

    files = os.listdir(input_folder)
    log.write(f"检测到 {len(files)} 个文件: {files}\n\n")

    count = 0
    for filename in files:
        if not filename.lower().endswith(".json"):
            continue

        input_path = os.path.join(input_folder, filename)
        output_path = os.path.join(output_folder, filename)

        # 提取第二段单词作为 replacer，如果不存在就跳过
        filename_no_ext = filename.rsplit(".", 1)[0]  # 去掉扩展名
        parts = filename_no_ext.split("_")
        if len(parts) < 2:
            log.write(f"⚠️ 跳过 {filename}（没有第二段单词）\n")
            continue
        replacer = parts[1]

        try:
            with open(input_path, "r", encoding="utf-8") as f:
                content = f.read()
        except Exception as e:
            log.write(f"无法读取 {filename}: {e}\n")
            continue

        if "leggings" not in content:
            log.write(f"跳过 {filename}（无 'leggings'）\n")
            continue

        new_content = re.sub(r'leggings', replacer, content)
        with open(output_path, "w", encoding="utf-8") as f:
            f.write(new_content)

        log.write(f"✅ 已处理: {filename} → 替换为 '{replacer}'\n")
        count += 1

    if count == 0:
        log.write("⚠️ 没有文件被修改，可能没有找到 'leggings'。\n")
    else:
        log.write(f"\n🎉 全部替换完成！共修改 {count} 个文件。\n")

print(f"处理完成！请查看 {log_path} 文件以获取详细信息。")