from aiogram import types


def get_response(message: types.Message):
    answer_en = get_translation(' '.join(message.text.split()[1:]), "en")
    print(answer_en)
    response_en = get_response_to_openai(answer_en)
    print(response_en)
    response_ru = get_translation(response_en, "ru")
    resource_ru_not_translate = get_response_to_openai(' '.join(message.text.split()[1:]))
    save_file(response_ru, resource_ru_not_translate)


def get_translation(text, language):
    from deep_translator import GoogleTranslator
    return GoogleTranslator(target=language).translate(text)


def get_response_to_openai(text):
    import openai
    openai.api_key = "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"
    response = openai.Completion.create(
        model="text-davinci-003",
        prompt=text,
        temperature=0.5,
        max_tokens=1000,
        top_p=1.0,
        frequency_penalty=0.5,
        presence_penalty=0.0
    )
    return response['choices'][0]['text']


def save_file(response_ru, resource_ru_not_translate):
    with open('response_ru.txt', 'w') as f:
        f.write(response_ru)
    with open('resource_ru_not_translate.txt', 'w') as f:
        f.write(resource_ru_not_translate)
