import json
import re

input_file = "storage-files/posts.json"
output_file = "storage-files/posts.json"

def fix_post_title(title: str, type_: str) -> str:
    original = title.strip()

    # حذف پیشوندهای قدیمی
    new_title = re.sub(r"^(فیلم ترکی |فیلم |سریال ترکی |سریال )", "", original)

    # اضافه کردن پیشوند درست بر اساس type
    if type_ == "movies":
        new_title = f"فیلم ترکی {new_title}"
    elif type_ == "series":
        new_title = f"سریال ترکی {new_title}"
    else:
        # اگر type چیز دیگه بود، بدون تغییر
        new_title = original

    # نمایش تغییرات به صورت diff
    if new_title != original:
        print("```diff")
        print(f'- "post_title": "{original}",')
        print(f'+ "post_title": "{new_title}",')
        print("```")
        print()

    return new_title

# خواندن JSON
with open(input_file, "r", encoding="utf-8") as f:
    data = json.load(f)

def process_json(obj):
    if isinstance(obj, dict):
        type_ = obj.get("type", None)
        for key, value in obj.items():
            if key == "post_title" and isinstance(value, str) and type_:
                obj[key] = fix_post_title(value, type_)
            else:
                process_json(value)
    elif isinstance(obj, list):
        for item in obj:
            process_json(item)

process_json(data)

# ذخیره خروجی با یونیکد
with open(output_file, "w", encoding="utf-8") as f:
    json.dump(data, f, ensure_ascii=True, indent=2)

print("\n✅ فایل fixed-post.json با موفقیت ساخته شد (خروجی با یونیکد).")
