import json
import urllib.request
import urllib.parse
import time
import sys

def translate_ru_to_ua(text):
    if not text:
        return text
    try:
        url = 'https://translate.googleapis.com/translate_a/single?client=gtx&sl=ru&tl=uk&dt=t&q=' + urllib.parse.quote(text)
        req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
        response = urllib.request.urlopen(req)
        data = json.loads(response.read().decode('utf-8'))
        translated_text = "".join([sentence[0] for sentence in data[0]])
        return translated_text
    except Exception as e:
        print(f"Error translating '{text}': {e}", file=sys.stderr)
        return text

def process_dict(d):
    for k, v in d.items():
        if isinstance(v, dict):
            if "ru" in v and "ua" in v:
                if v["ru"] == v["ua"] or v["ua"] == "" or "язык" in v["ua"].lower() or "пароль" in v["ua"].lower() or "почт" in v["ua"].lower() or "забыли" in v["ua"].lower():
                    # Check if actually same or mostly Russian wording
                    if v["ru"]:
                        v["ua"] = translate_ru_to_ua(v["ru"])
                        time.sleep(0.3)
            process_dict(v)

if __name__ == "__main__":
    with open('src/locales/translations.json', 'r', encoding='utf-8') as f:
        data = json.load(f)
    process_dict(data)
    with open('src/locales/translations.json', 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)
    print("Done")
