#!/usr/bin/env python3
"""
Final comprehensive translation script for remaining keys.
This handles all the keys that still need translation.
"""

import json

# Final comprehensive translations
FINAL_JA = {
    "OK": "OK",  # Keep as is, it's commonly used in Japanese UI
    "Reset Prompt": "プロンプトをリセット",
    "Are you sure you want to reset this prompt to the default admin configuration?": "このプロンプトをデフォルトの管理者設定にリセットしてもよろしいですか？",
    "Delete My Account Permanently": "アカウントを完全に削除",
    "Delete Account": "アカウントを削除",
    "Type \"DELETE\" to confirm": "\"削除\"と入力して確認",
    "This action cannot be undone. All your data will be permanently deleted.": "この操作は元に戻せません。すべてのデータが永久に削除されます。",
    "Current Email": "現在のメール",
    "New Email Address": "新しいメールアドレス",
    "Current Password": "現在のパスワード",
    "Send Verification Email": "確認メールを送信",
    "Update your email address. You will need to verify the new email before it takes effect.": "メールアドレスを更新します。新しいメールを確認する必要があります。",
    "Change Email Address": "メールアドレスを変更",
    "Bitcoin Configuration": "Bitcoin設定",
    "Coinbase Commerce Configuration": "Coinbase Commerce設定",
    "Critical Security Setting": "重要なセキュリティ設定",
    "Crypto Price Sources": "暗号通貨価格ソース",
    "Currency Code": "通貨コード",
    "Important Note About Currency Selection": "通貨選択に関する重要な注意事項",
    "Global Currency Settings": "グローバル通貨設定",
    "Currency Symbol": "通貨記号",
    "Decimal Places": "小数点以下桁数",
    "Encryption Key Configuration": "暗号化キー設定",
    "Ethereum Configuration": "Ethereum設定",
    "Admin Address": "管理者アドレス",
    "Client ID": "クライアントID",
    "Client Secret": "クライアントシークレット",
    "Contract Address": "コントラクトアドレス",
    "Failed Payments": "失敗した支払い",
    "Minimum Confirmations": "最小確認数",
    "Monitoring Method": "監視方法",
    "Network": "ネットワーク",
    "Pending Payments": "保留中の支払い",
    "Secret Key": "シークレットキー",
    "Threshold Amount": "閾値金額",
    "Total Balance": "合計残高",
    "Wallet Address": "ウォレットアドレス",
    "Bitcoin (BTC)": "ビットコイン (BTC)",
    "Ethereum (ETH), USDC, USDT (ERC20, Mainnet)": "イーサリアム (ETH)、USDC、USDT (ERC20、メインネット)",
    "Billing & Payments": "請求と支払い",
    "Add Card": "カードを追加",
    "Cancel": "キャンセル",
    "Credit Card": "クレジットカード",
    "Bitcoin": "ビットコイン",
    "Ethereum": "イーサリアム",
    "PayPal": "PayPal",
    "USDC": "USDC",
    "USDT": "USDT",
    "All subscription renewals and payments are automatically charged from your wallet first.": "すべてのサブスクリプション更新と支払いは、最初にウォレットから自動的に請求されます。",
    "Save": "保存",
    "Cache Settings": "キャッシュ設定",
    "Permanently delete your account and all associated data.": "アカウントと関連するすべてのデータが永久に削除されます。",
    "Are you absolutely sure? This action cannot be undone and all your data will be permanently deleted.": "本当によろしいですか？この操作は元に戻せず、すべてのデータが永久に削除されます。",
    "Consider canceling your subscription first if you want to use it until the end of the billing period.": "請求期間の終了まで使用したい場合は、最初にサブスクリプションをキャンセルすることを検討してください。",
    "You have an active paid subscription ({tier}). Deleting your account will:": "アクティブな有料サブスクリプション（{tier}）があります。アカウントを削除すると次のようになります：",
    "Please type \"DELETE\" exactly to confirm account deletion.": "アカウント削除を確認するには、\"削除\"と正確に入力してください。",
}

FINAL_ZH = {
    "OK": "确定",
    "Reset Prompt": "重置提示词",
    "Are you sure you want to reset this prompt to the default admin configuration?": "您确定要将此提示词重置为默认管理员配置吗？",
    "Delete My Account Permanently": "永久删除我的账户",
    "Delete Account": "删除账户",
    "Type \"DELETE\" to confirm": "输入\"删除\"以确认",
    "This action cannot be undone. All your data will be permanently deleted.": "此操作无法撤消，所有数据将被永久删除。",
    "Current Email": "当前邮箱",
    "New Email Address": "新邮箱地址",
    "Current Password": "当前密码",
    "Send Verification Email": "发送验证邮件",
    "Update your email address. You will need to verify the new email before it takes effect.": "更新您的邮箱地址。您需要验证新邮箱后才能生效。",
    "Change Email Address": "更改邮箱地址",
    "Bitcoin Configuration": "比特币配置",
    "Coinbase Commerce Configuration": "Coinbase Commerce配置",
    "Critical Security Setting": "关键安全设置",
    "Crypto Price Sources": "加密货币价格来源",
    "Currency Code": "货币代码",
    "Important Note About Currency Selection": "关于货币选择的重要说明",
    "Global Currency Settings": "全局货币设置",
    "Currency Symbol": "货币符号",
    "Decimal Places": "小数位数",
    "Encryption Key Configuration": "加密密钥配置",
    "Ethereum Configuration": "以太坊配置",
    "Admin Address": "管理员地址",
    "Client ID": "客户端ID",
    "Client Secret": "客户端密钥",
    "Contract Address": "合约地址",
    "Failed Payments": "失败支付",
    "Minimum Confirmations": "最少确认数",
    "Monitoring Method": "监控方式",
    "Network": "网络",
    "Pending Payments": "待处理支付",
    "Secret Key": "密钥",
    "Threshold Amount": "阈值金额",
    "Total Balance": "总余额",
    "Wallet Address": "钱包地址",
    "Bitcoin (BTC)": "比特币 (BTC)",
    "Ethereum (ETH), USDC, USDT (ERC20, Mainnet)": "以太坊 (ETH)、USDC、USDT (ERC20、主网)",
    "Billing & Payments": "账单与支付",
    "Add Card": "添加卡片",
    "Cancel": "取消",
    "Credit Card": "信用卡",
    "Bitcoin": "比特币",
    "Ethereum": "以太坊",
    "PayPal": "PayPal",
    "USDC": "USDC",
    "USDT": "USDT",
    "All subscription renewals and payments are automatically charged from your wallet first.": "所有订阅续订和付款都将首先从您的钱包中自动扣除。",
    "Save": "保存",
    "Cache Settings": "缓存设置",
    "Permanently delete your account and all associated data.": "永久删除您的账户及所有相关数据。",
    "Are you absolutely sure? This action cannot be undone and all your data will be permanently deleted.": "您确定吗？此操作无法撤消，并且所有数据将被永久删除。",
    "Consider canceling your subscription first if you want to use it until the end of the billing period.": "如果您想使用到计费期结束，请考虑先取消订阅。",
    "You have an active paid subscription ({tier}). Deleting your account will:": "您有一个活跃的付费订阅 ({tier})。删除您的账户将：",
    "Please type \"DELETE\" exactly to confirm account deletion.": "请准确输入 \"DELETE\" 以确认删除账户。",
}

FINAL_KO = {
    "OK": "OK",
    "Reset Prompt": "프롬프트 재설정",
    "Are you sure you want to reset this prompt to the default admin configuration?": "이 프롬프트를 기본 관리자 구성으로 재설정하시겠습니까?",
    "Delete My Account Permanently": "내 계정 영구 삭제",
    "Delete Account": "계정 삭제",
    "Type \"DELETE\" to confirm": "\"삭제\"를 입력하여 확인",
    "This action cannot be undone. All your data will be permanently deleted.": "이 작업은 취소할 수 없으며 모든 데이터가 영구적으로 삭제됩니다.",
    "Current Email": "현재 이메일",
    "New Email Address": "새 이메일 주소",
    "Current Password": "현재 비밀번호",
    "Send Verification Email": "확인 이메일 보내기",
    "Update your email address. You will need to verify the new email before it takes effect.": "이메일 주소를 업데이트합니다. 새 이메일을 확인해야 합니다.",
    "Change Email Address": "이메일 주소 변경",
    "Bitcoin Configuration": "Bitcoin 구성",
    "Coinbase Commerce Configuration": "Coinbase Commerce 구성",
    "Critical Security Setting": "중요 보안 설정",
    "Crypto Price Sources": "암호화폐 가격 소스",
    "Currency Code": "통화 코드",
    "Important Note About Currency Selection": "통화 선택에 대한 중요 안내",
    "Global Currency Settings": "전체 통화 설정",
    "Currency Symbol": "통화 기호",
    "Decimal Places": "소수점 이하 자릿수",
    "Encryption Key Configuration": "암호화 키 구성",
    "Ethereum Configuration": "Ethereum 구성",
    "Admin Address": "관리자 주소",
    "Client ID": "클라이언트 ID",
    "Client Secret": "클라이언트 시크릿",
    "Contract Address": "컨트랙트 주소",
    "Failed Payments": "실패한 결제",
    "Minimum Confirmations": "최소 확인 수",
    "Monitoring Method": "모니터링 방법",
    "Network": "네트워크",
    "Pending Payments": "대기 중인 결제",
    "Secret Key": "시크릿 키",
    "Threshold Amount": "임계값 금액",
    "Total Balance": "총 잔액",
    "Wallet Address": "지갑 주소",
    "Bitcoin (BTC)": "비트코인 (BTC)",
    "Ethereum (ETH), USDC, USDT (ERC20, Mainnet)": "이더리움 (ETH), USDC, USDT (ERC20, 메인넷)",
    "Billing & Payments": "결제 및 청구",
    "Add Card": "카드 추가",
    "Cancel": "취소",
    "Credit Card": "신용카드",
    "Bitcoin": "비트코인",
    "Ethereum": "이더리움",
    "PayPal": "PayPal",
    "USDC": "USDC",
    "USDT": "USDT",
    "All subscription renewals and payments are automatically charged from your wallet first.": "모든 구독 갱신 및 결제는 먼저 지갑에서 자동으로 청구됩니다.",
    "Save": "저장",
    "Cache Settings": "캐시 설정",
    "Permanently delete your account and all associated data.": "계정 및 관련 데이터가 영구적으로 삭제됩니다.",
    "Are you absolutely sure? This action cannot be undone and all your data will be permanently deleted.": "정말 확실합니까? 이 작업은 취소할 수 없으며 모든 데이터가 영구적으로 삭제됩니다.",
    "Consider canceling your subscription first if you want to use it until the end of the billing period.": "청구 기간이 끝날 때까지 사용하려면 먼저 구독을 취소하는 것을 고려해 보세요.",
    "You have an active paid subscription ({tier}). Deleting your account will:": "활성 유료 구독({tier})이 있습니다. 계정을 삭제하면 다음과 같은 일이 발생합니다:",
    "Please type \"DELETE\" exactly to confirm account deletion.": "계정 삭제를 확인하려면 정확히 \"삭제\"를 입력하세요.",
}

FINAL_RU = {
    "OK": "OK",
    "Reset Prompt": "Сбросить промпт",
    "Are you sure you want to reset this prompt to the default admin configuration?": "Вы уверены, что хотите сбросить этот промпт до конфигурации по умолчанию?",
    "Delete My Account Permanently": "Удалить мой аккаунт навсегда",
    "Delete Account": "Удалить аккаунт",
    "Type \"DELETE\" to confirm": "Введите \"DELETE\" для подтверждения",
    "This action cannot be undone. All your data will be permanently deleted.": "Это действие невозможно отменить. Все ваши данные будут удалены навсегда.",
    "Current Email": "Текущий email",
    "New Email Address": "Новый email",
    "Current Password": "Текущий пароль",
    "Send Verification Email": "Отправить письмо подтверждения",
    "Update your email address. You will need to verify the new email before it takes effect.": "Обновите ваш email. Вам нужно будет подтвердить новый email, прежде чем он вступит в силу.",
    "Change Email Address": "Изменить email",
    "Bitcoin Configuration": "Bitcoin конфигурация",
    "Coinbase Commerce Configuration": "Coinbase Commerce конфигурация",
    "Critical Security Setting": "Критическая настройка безопасности",
    "Crypto Price Sources": "Источники цен на криптовалюты",
    "Currency Code": "Код валюты",
    "Important Note About Currency Selection": "Важное примечание о выборе валюты",
    "Global Currency Settings": "Глобальные настройки валют",
    "Currency Symbol": "Символ валюты",
    "Decimal Places": "Десятичные знаки",
    "Encryption Key Configuration": "Настройка ключа шифрования",
    "Ethereum Configuration": "Ethereum конфигурация",
    "Admin Address": "Адрес администратора",
    "Client ID": "ID клиента",
    "Client Secret": "Секрет клиента",
    "Contract Address": "Адрес контракта",
    "Failed Payments": "Неудачные платежи",
    "Minimum Confirmations": "Минимальное количество подтверждений",
    "Monitoring Method": "Метод мониторинга",
    "Network": "Сеть",
    "Pending Payments": "Ожидающие платежи",
    "Secret Key": "Секретный ключ",
    "Threshold Amount": "Пороговая сумма",
    "Total Balance": "Общий баланс",
    "Wallet Address": "Адрес кошелька",
    "Bitcoin (BTC)": "Bitcoin (BTC)",
    "Ethereum (ETH), USDC, USDT (ERC20, Mainnet)": "Ethereum (ETH), USDC, USDT (ERC20, Mainnet)",
    "Billing & Payments": "Выставление счетов и оплаты",
    "Add Card": "Добавить карту",
    "Cancel": "Отмена",
    "Credit Card": "Кредитная карта",
    "Bitcoin": "Bitcoin",
    "Ethereum": "Ethereum",
    "PayPal": "PayPal",
    "USDC": "USDC",
    "USDT": "USDT",
    "All subscription renewals and payments are automatically charged from your wallet first.": "Все продления подписки и платежи сначала автоматически списываются с вашего кошелька.",
    "Save": "Сохранить",
    "Cache Settings": "Настройки кэша",
    "Permanently delete your account and all associated data.": "Ваш аккаунт и все связанные данные будут удалены навсегда.",
    "Are you absolutely sure? This action cannot be undone and all your data will be permanently deleted.": "Вы абсолютно уверены? Это действие невозможно отменить, и все ваши данные будут удалены навсегда.",
    "Consider canceling your subscription first if you want to use it until the end of the billing period.": "Если вы хотите использовать подписку до конца периода оплаты, сначала рассмотрите возможность ее отмены.",
    "You have an active paid subscription ({tier}). Deleting your account will:": "У вас есть активная платная подписка ({tier}). Удаление вашего аккаунта приведет к:",
    "Please type \"DELETE\" exactly to confirm account deletion.": "Пожалуйста, введите \"DELETE\" точно для подтверждения удаления аккаунта.",
}

FINAL_AF = {
    "OK": "OK",
    "Reset Prompt": "Stel prompterfris",
    "Are you sure you want to reset this prompt to the default admin configuration?": "Is u seker dat u hierdie promt na die verstek-administrateurkonfigurasie wil stel?",
    "Delete My Account Permanently": "Verwyder my rekening permanent",
    "Delete Account": "Verwyder rekening",
    "Type \"DELETE\" to confirm": "Tik \"DELETE\" in om te bevestig",
    "This action cannot be undone. All your data will be permanently deleted.": "Hierdie aksie kan nie ontdoen word nie. Al jou data sal permanent uitgevee word.",
    "Current Email": "Huidige e-pos",
    "New Email Address": "Nuwe e-posadres",
    "Current Password": "Huidige wagwoord",
    "Send Verification Email": "Stuur verifikasie-e-pos",
    "Update your email address. You will need to verify the new email before it takes effect.": "Dateer u e-posadres op. U moet die nuwe e-pos verifieer voordat dit in werking treed.",
    "Change Email Address": "Verander e-posadres",
    "Bitcoin Configuration": "Bitcoin konfigurasie",
    "Coinbase Commerce Configuration": "Coinbase Commerce konfigurasie",
    "Critical Security Setting": "Kritieke sekuriteitinstelling",
    "Crypto Price Sources": "Kriptoprysbronne",
    "Currency Code": "Geldkode",
    "Important Note About Currency Selection": "Belangrike opmerking oor geldkies",
    "Global Currency Settings": "Globale geldeenheidinstellings",
    "Currency Symbol": "Geldeenheidsimbool",
    "Decimal Places": "Desimale plekke",
    "Encryption Key Configuration": "Enkripsiesleutelkonfigurasie",
    "Ethereum Configuration": "Ethereum konfigurasie",
    "Admin Address": "Admin adres",
    "Client ID": "Kliënt-ID",
    "Client Secret": "Kliëntgeheim",
    "Contract Address": "Kontrakadres",
    "Failed Payments": "Mislukte betalings",
    "Minimum Confirmations": "Minimum bevestigings",
    "Monitoring Method": "Monitormetode",
    "Network": "Netwerk",
    "Pending Payments": "Hangende betalings",
    "Secret Key": "Geheime sleutel",
    "Threshold Amount": "Drempelbedrag",
    "Total Balance": "Totale balans",
    "Wallet Address": "Beursieadres",
    "Bitcoin (BTC)": "Bitcoin (BTC)",
    "Ethereum (ETH), USDC, USDT (ERC20, Mainnet)": "Ethereum (ETH), USDC, USDT (ERC20, Mainnet)",
    "Billing & Payments": "Fakturering en betalings",
    "Add Card": "Voeg kaart by",
    "Cancel": "Kanselleer",
    "Credit Card": "Kredietkaart",
    "Bitcoin": "Bitcoin",
    "Ethereum": "Ethereum",
    "PayPal": "PayPal",
    "USDC": "USDC",
    "USDT": "USDT",
    "All subscription renewals and payments are automatically charged from your wallet first.": "Alle intekeningsvernuwings en betalings word eers outomaties van u beursie afgeskryf.",
    "Save": "Stoor",
    "Cache Settings": "Kasinstellings",
    "Permanently delete your account and all associated data.": "U rekening en alle geassosieerde data sal permanent uitgevee word.",
    "Are you absolutely sure? This action cannot be undone and all your data will be permanently deleted.": "Is u absoluut seker? Hierdie aksie kan nie ontdoen word nie en al u data sal permanent uitgevee word.",
    "Consider canceling your subscription first if you want to use it until the end of the billing period.": "Oorweeg om u intekening eerste te kanselleer as u dit tot die einde van die faktureringsperiode wil gebruik.",
    "You have an active paid subscription ({tier}). Deleting your account will:": "U het 'n aktiewe betaalde intekening ({tier}). As u u rekening uitvee, sal dit:",
    "Please type \"DELETE\" exactly to confirm account deletion.": "Tik asseblief presies \"DELETE\" in om rekeninguit te vee te bevestig.",
}

def apply_final_translations(lang_code, translations):
    """Apply final translations to a language file"""
    filepath = f'/working/aisbf/static/i18n/{lang_code}.json'
    
    with open(filepath, 'r', encoding='utf-8') as f:
        data = json.load(f)
    
    changes = []
    
    def update_dict(d, path=""):
        for key, value in d.items():
            current_path = f"{path}.{key}" if path else key
            if isinstance(value, dict):
                update_dict(value, current_path)
            elif isinstance(value, str) and value in translations:
                old_value = value
                d[key] = translations[value]
                changes.append((current_path, old_value, d[key]))
    
    update_dict(data)
    
    with open(filepath, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)
    
    return changes

if __name__ == '__main__':
    languages = [
        ('ja', FINAL_JA),
        ('zh', FINAL_ZH),
        ('ko', FINAL_KO),
        ('ru', FINAL_RU),
        ('af', FINAL_AF),
    ]
    
    total = 0
    for lang_code, translations in languages:
        changes = apply_final_translations(lang_code, translations)
        total += len(changes)
        if changes:
            print(f"\n{lang_code.upper()}: {len(changes)} changes")
            for path, old, new in changes[:10]:
                print(f"  {path}")
                print(f"    {old} -> {new}")
    
    print(f"\n{'='*60}")
    print(f"TOTAL FINAL TRANSLATIONS: {total}")
    print(f"{'='*60}")