#!/usr/bin/env python3
"""Fill missing locale keys.
- en.json: extract English text from each template's  t('key') | default('TEXT')  fallback.
- tr/ar:   payout_wallet  (manual).
- all:     join_tournament_long (manual translations).
Idempotent: never overwrites existing keys.
"""
import json, os, re, html

BASE = '/home/z/my-project/fightskill'
TPL = os.path.join(BASE, 'app', 'templates')
LOC = os.path.join(BASE, 'app', 'i18n', 'locales')

# ── 1. Harvest default() fallback texts from templates ──────────────
pat = re.compile(r"""(?<![A-Za-z0-9_])t\('([a-z][a-z0-9_]*)'\)\s*\|\s*default\(\s*(['"])(.*?)\2""", re.S)
harvest = {}
for root, _dirs, files in os.walk(TPL):
    for fn in files:
        if not fn.endswith('.html'):
            continue
        p = os.path.join(root, fn)
        with open(p, encoding='utf-8') as f:
            txt = f.read()
        for m in pat.finditer(txt):
            key, text = m.group(1), m.group(3)
            text = html.unescape(text).strip()
            # strip surrounding quotes already consumed; keep single-line
            text = re.sub(r'\s+', ' ', text)
            if text and key not in harvest:
                harvest[key] = text

# ── 2. Manual translations for keys with no template default ────────
MANUAL = {
    "en": {
        "actions": "Actions", "agree_terms": "I agree to the Terms of Service and Privacy Policy",
        "already_have_account": "Already have an account?", "available_slots": "Available slots",
        "back_to_login": "Back to login", "charge": "Charge", "click_code": "Click to show/copy (dev mode)",
        "closed": "Closed", "created": "Created", "description": "Description", "earned": "Earned",
        "group_reg": "Group Registration", "group_reg_desc": "Register together as a team or group",
        "leaderboard_desc": "Compete for the top and earn exclusive rewards.",
        "manage": "Manage", "mark_as_read": "Mark as read", "members": "Members",
        "my_games": "My Games", "name": "Name", "no_friends": "No team members yet — invite friends from the Team page.",
        "no_matches": "No matches found", "no_special_matches": "No special matches right now. Check back soon!",
        "no_video": "Tutorial video for your language is coming soon.",
        "online": "Online", "reset_code_sent": "Reset code sent! Check your inbox.",
        "reset_password": "Reset Password", "save_password": "Save Password",
        "select_game_first": "Select a game first", "send_reset_code": "Send Reset Code",
        "social": "Social", "special_desc": "Exclusive high-stakes tournaments with bigger prize pools.",
        "squad_size": "Squad size", "support_desc": "Our support team replies inside the app — usually within an hour.",
        "support_team": "Support Team", "team_desc": "Create or join a team and climb together.",
        "unread": "Unread", "user_not_found": "User not found.",
        "wallet_desc": "Deposit wallet for entries, payout wallet for prizes.",
        "winners": "Winners", "your_team_members": "Your team members",
        "prize_distribution": "Prize Distribution",
        "prize_by_rank_note": "Prizes are paid per rank and shown here once winners are announced.",
    },
    "fa": {
        "join_tournament_long": "تورنمنت‌ها را مرور کنید، ثبت‌نام کنید و در مسابقات حرفه‌ای رقابت کنید.",
        "payout_wallet": "کیف پول برداشت",
        "prize_by_rank_note": "جوایز بر اساس مقام پرداخت می‌شود و پس از اعلام برندگان اینجا نمایش داده می‌شود.",
        "my_games": "بازی‌های من", "name": "نام",
        "no_friends": "هنوز عضوی در تیم نیست — از صفحه تیم دوستانتان را دعوت کنید.",
        "no_matches": "مسابقه‌ای یافت نشد", "no_special_matches": "در حال حاضر مسابقه ویژه‌ای نیست. به‌زودی برگردید!",
        "no_video": "ویدیوی آموزشی به زبان شما به‌زودی اضافه می‌شود.",
        "reset_code_sent": "کد بازیابی ارسال شد! صندوق ورودی خود را بررسی کنید.",
        "save_password": "ذخیره رمز عبور", "select_game_first": "اول یک بازی انتخاب کنید",
        "social": "شبکه‌های اجتماعی",
        "special_desc": "تورنمنت‌های اختصاصی با جایزه‌های بزرگ‌تر.",
        "squad_size": "اندازه اسکواد", "support_desc": "تیم پشتیبانی ما داخل خود اپلیکیشن پاسخ می‌دهد — معمولاً در کمتر از یک ساعت.",
        "team_desc": "تیم بسازید یا به تیمی بپیوندید و با هم بالا بروید.",
        "user_not_found": "کاربر یافت نشد.",
        "wallet_desc": "کیف ورودی برای ثبت‌نام، کیف برداشت برای جوایز.",
        "your_team_members": "اعضای تیم شما",
    },
    "tr": {
        "join_tournament_long": "Turnuvalara göz at, kaydol ve profesyonel maçlarda yarış.",
        "payout_wallet": "Çekim Cüzdanı",
        "prize_by_rank_note": "Ödüller sıralamaya göre ödenir ve kazananlar açıklandığında burada gösterilir.",
        "my_games": "Oyunlarım", "name": "İsim",
        "no_friends": "Henüz takım üyesi yok — Takım sayfasından arkadaşlarını davet et.",
        "no_matches": "Maç bulunamadı", "no_special_matches": "Şu anda özel maç yok. Yakında tekrar kontrol et!",
        "no_video": "Dilinize özel eğitim videosu yakında eklenecek.",
        "reset_code_sent": "Sıfırlama kodu gönderildi! Gelen kutunu kontrol et.",
        "save_password": "Şifreyi Kaydet", "select_game_first": "Önce bir oyun seç",
        "social": "Sosyal Medya",
        "special_desc": "Daha büyük ödül havuzlarına sahip özel turnuvalar.",
        "squad_size": "Takım boyutu", "support_desc": "Destek ekibimiz uygulama içinde yanıtlar — genellikle bir saat içinde.",
        "team_desc": "Takım kur veya bir takıma katıl ve birlikte yüksel.",
        "user_not_found": "Kullanıcı bulunamadı.",
        "wallet_desc": "Kayıtlar için giriş cüzdanı, ödüller için çekim cüzdanı.",
        "your_team_members": "Takım üyelerin",
    },
    "ar": {
        "join_tournament_long": "تصفح البطولات وسجّل ونافس في مباريات احترافية.",
        "payout_wallet": "محفظة السحب",
        "prize_by_rank_note": "تُدفع الجوائز حسب المركز وتُعرض هنا عند الإعلان عن الفائزين.",
        "my_games": "ألعابي", "name": "الاسم",
        "no_friends": "لا أعضاء في الفريق بعد — ادعُ أصدقاءك من صفحة الفريق.",
        "no_matches": "لا توجد مباريات", "no_special_matches": "لا مباريات خاصة حاليًا. عد قريبًا!",
        "no_video": "سيتم قريبًا إضافة فيديو تعليمي بلغتك.",
        "reset_code_sent": "تم إرسال رمز الاستعادة! تحقق من بريدك.",
        "save_password": "حفظ كلمة المرور", "select_game_first": "اختر لعبة أولاً",
        "social": "التواصل الاجتماعي",
        "special_desc": "بطولات حصرية بجوائز أكبر.",
        "squad_size": "حجم الفريق", "support_desc": "يفيد فريق الدعم داخل التطبيق — عادة خلال ساعة.",
        "team_desc": "أنشئ فريقًا أو انضم إلى فريق وتسلقوا معًا.",
        "user_not_found": "المستخدم غير موجود.",
        "wallet_desc": "محفظة الإيداع للتسجيل، ومحفظة السحب للجوائز.",
        "your_team_members": "أعضاء فريقك",
    },
}

for lang in ("en", "fa", "tr", "ar"):
    path = os.path.join(LOC, f"{lang}.json")
    with open(path, encoding="utf-8") as f:
        data = json.load(f)
    added = 0
    # a) template-harvested defaults (EN source of truth)
    if lang == "en":
        for k, v in harvest.items():
            if k not in data:
                data[k] = v
                added += 1
    # b) manual keys
    for k, v in MANUAL.get(lang, {}).items():
        if k not in data:
            data[k] = v
            added += 1
    with open(path, "w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=2)
        f.write("\n")
    print(f"{lang}.json: +{added} -> {len(data)} total keys")
print("DONE")
