# -*- coding: utf-8 -*-
"""补翻 YuemuCloudAssets fr-FR.json 中仍为英文的条目（限流重试）"""
import json
import os
import time

from deep_translator import MyMemoryTranslator
from deep_translator.exceptions import TooManyRequests

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
RES = os.path.join(ROOT, 'YuemuCloudAssets', 'languages', 'resources')
BATCH = 15


def translate_batch_retry(translator, values, retries=5):
    for attempt in range(retries):
        try:
            return translator.translate_batch(values)
        except TooManyRequests:
            wait = 3 * (attempt + 1)
            print(f'  rate limited, wait {wait}s...', flush=True)
            time.sleep(wait)
        except Exception as e:
            print(f'  batch error: {e}', flush=True)
            break
    return None


def main():
    en_path = os.path.join(RES, 'en-US.json')
    fr_path = os.path.join(RES, 'fr-FR.json')
    with open(en_path, encoding='utf-8') as f:
        en_data = json.load(f)
    with open(fr_path, encoding='utf-8') as f:
        fr_data = json.load(f)

    todo_vals = []
    seen = set()
    for k, en_val in en_data.items():
        s = en_val if isinstance(en_val, str) else str(en_val)
        if fr_data.get(k) == en_val and s not in seen:
            seen.add(s)
            todo_vals.append(s)

    print(f'Need translate: {len(todo_vals)} unique strings', flush=True)
    if not todo_vals:
        return

    translator = MyMemoryTranslator(source='en-US', target='fr-FR')
    mapping = {}
    chunks = [todo_vals[i:i + BATCH] for i in range(0, len(todo_vals), BATCH)]
    for i, chunk in enumerate(chunks, 1):
        translated = translate_batch_retry(translator, chunk)
        if translated is None:
            print(f'  batch {i}/{len(chunks)} skipped (rate limit)', flush=True)
            time.sleep(30)
            continue
        for src, dst in zip(chunk, translated):
            if dst and dst != src:
                mapping[src] = dst
        print(f'  batch {i}/{len(chunks)} ok', flush=True)
        time.sleep(2.0)

    for k, en_val in en_data.items():
        s = en_val if isinstance(en_val, str) else str(en_val)
        if fr_data.get(k) == en_val and s in mapping:
            fr_data[k] = mapping[s]

    with open(fr_path, 'w', encoding='utf-8') as f:
        json.dump(dict(sorted(fr_data.items())), f, ensure_ascii=False, indent=2)

    same = sum(1 for k in en_data if fr_data.get(k) == en_data.get(k))
    print(f'Done. unchanged vs en-US: {same}/{len(en_data)}', flush=True)


if __name__ == '__main__':
    main()
