# -*- coding: utf-8 -*-
"""从 en-US.json 快速生成 fr-FR / es-ES / vi-VN（去重 + 批量机翻）"""
import json
import os
import sys
import time
from concurrent.futures import ThreadPoolExecutor, as_completed

from deep_translator import MyMemoryTranslator

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TARGETS = [
    ('fr-FR', 'fr-FR'),
    ('es-ES', 'es-ES'),
    ('vi-VN', 'vi-VN'),
]
BATCH_SIZE = 15
WORKERS = 1  # 并行易触发 MyMemory 限流，单线程更稳


def translate_batch(values, target_code):
    if not values:
        return []
    translator = MyMemoryTranslator(source='en-US', target=target_code)
    try:
        if hasattr(translator, 'translate_batch'):
            return translator.translate_batch(values)
    except Exception:
        pass
    out = []
    for v in values:
        try:
            out.append(translator.translate(v))
        except Exception:
            out.append(v)
    return out


def translate_unique(unique_vals, target_code):
    mapping = {}
    chunks = [unique_vals[i:i + BATCH_SIZE] for i in range(0, len(unique_vals), BATCH_SIZE)]
    total = len(chunks)
    with ThreadPoolExecutor(max_workers=WORKERS) as pool:
        futures = {pool.submit(translate_batch, chunk, target_code): idx for idx, chunk in enumerate(chunks)}
        for fut in as_completed(futures):
            idx = futures[fut]
            chunk = chunks[idx]
            try:
                translated = fut.result()
            except Exception as e:
                print(f'  batch {idx + 1}/{total} failed: {e}', file=sys.stderr)
                translated = chunk
            for src, dst in zip(chunk, translated):
                mapping[src] = dst if dst else src
            print(f'  [{target_code}] batch {idx + 1}/{total}', flush=True)
            time.sleep(1.5)
    return mapping


def build_locale(en_path, out_path, target_code, force=False):
    if os.path.isfile(out_path) and not force:
        print(f'Skip existing {out_path}')
        return
    with open(en_path, encoding='utf-8') as f:
        en_data = json.load(f)
    unique = []
    seen = set()
    for val in en_data.values():
        s = val if isinstance(val, str) else str(val)
        if s not in seen:
            seen.add(s)
            unique.append(s)
    print(f'  unique strings: {len(unique)} / {len(en_data)}')
    mapping = translate_unique(unique, target_code)
    result = {k: mapping.get(v if isinstance(v, str) else str(v), v) for k, v in en_data.items()}
    os.makedirs(os.path.dirname(out_path), exist_ok=True)
    with open(out_path, 'w', encoding='utf-8') as f:
        json.dump(dict(sorted(result.items())), f, ensure_ascii=False, indent=2)
    print(f'Wrote {len(result)} -> {out_path}')


def main():
    force = '--force' in sys.argv
    sets = [
        (
            os.path.join(ROOT, 'languages', 'resources', 'en-US.json'),
            os.path.join(ROOT, 'languages', 'resources'),
        ),
        (
            os.path.join(ROOT, 'YuemuCloudAssets', 'languages', 'resources', 'en-US.json'),
            os.path.join(ROOT, 'YuemuCloudAssets', 'languages', 'resources'),
        ),
    ]
    for en_path, out_dir in sets:
        if not os.path.isfile(en_path):
            print(f'Skip missing {en_path}', file=sys.stderr)
            continue
        print(f'=== {en_path} ===')
        for locale_file, target_code in TARGETS:
            out_path = os.path.join(out_dir, f'{locale_file}.json')
            build_locale(en_path, out_path, target_code, force=force)


if __name__ == '__main__':
    main()
