from dotenv import dotenv_values
import openai

config = dotenv_values('.env')
openai.api_key = config.get('OPENAI_API_KEY')


class OpenAiChatCompletionClient:
    def __init__(self):
        self.response = None

    def send(self, prompt):
        messages = [{"role": "user", "content": prompt}]
        self.response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=messages,
            max_tokens=512,
            top_p=1,
            frequency_penalty=0,
            presence_penalty=0,
        )


class OpenAiTranslator(OpenAiChatCompletionClient):
    def __init__(self):
        super().__init__()

    def translate(self, word, context, language='Spanish'):
        context = context.strip()
        if not context.endswith(('.', '?', '!')):
            context += '.'

        prompt = "You will be given an English sentence, and a selected word that appears in that sentence. " \
            "Translate the sentence from English to {language}." \
            "If the selected word is part of an idiomatic expression, then mark the idiomatic expression instead. " \
            "Write a definition in {language} of the selected word or words. " \
            "Return a JSON object with the following keys: 'translation', 'definition'.\n\n" \
            "English sentence: \"{context}\"\n" \
            "selected word: \"{word}\"".format(word=word, context=context, language=language)

        self.send(prompt)
