import json
from aiogram import types
import sqlite3
import openai


async def get_response_to_openai(message: types.Message, bot):
    if message.from_user.id in json.load(open("not_work_user.json"))["chat_gpt"]:
        await bot.send_message(message.chat.id, "ПИШЁВ ТИ НАХУЙ")
        return
    conn = sqlite3.connect('db.sql')
    cur = conn.cursor()
    openai.api_key = "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"
    try:
        points = cur.execute("SELECT * FROM 'f'".replace("f", str(message.from_user.id))).fetchall()
        message_send = []
        for i in points:
            message_send.append({"role": i[1], "content": i[2]})
        message_send.append({"role": "user", "content": ' '.join(message.text.split()[1:])})
    except sqlite3.OperationalError:
        message_send = [{"role": "user", "content": ' '.join(message.text.split()[1:])}]
    print(message_sendко)
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=message_send,
        temperature=0.5,
        max_tokens=1000,
        top_p=1.0,
        frequency_penalty=0.5,
        presence_penalty=0.0
    )
    await bot.send_message(message.chat.id, f"ChatGPT\n{response['choices'][0]['message']['content']}",
                           parse_mode=None, reply_to_message_id=message.message_id)
    try:
        cur.execute("INSERT INTO 'f' (role, content) VALUES (?, ?)".replace("f", str(message.from_user.id)),
                    ("user", ' '.join(message.text.split()[1:])))
        cur.execute("INSERT INTO 'f' (role, content) VALUES (?, ?)".replace("f", str(message.from_user.id)),
                    ("assistant", response['choices'][0]['message']['content']))
        conn.commit()
        conn.close()
    except sqlite3.OperationalError:
        cur.execute(f"CREATE TABLE IF NOT EXISTS '{message.from_user.id}' (id INTEGER PRIMARY KEY AUTOINCREMENT"
                    f" UNIQUE NOT NULL, role STRING NOT NULL,"
                    f" content STRING NOT NULL)")
        cur.execute("INSERT INTO 'f' (role, content) VALUES (?, ?)".replace("f", str(message.from_user.id)),
                    ("user", ' '.join(message.text.split()[1:])))
        cur.execute("INSERT INTO 'f' (role, content) VALUES (?, ?)".replace("f", str(message.from_user.id)),
                    ("assistant", response['choices'][0]['message']['content']))
        conn.commit()
        conn.close()


async def clear_db(message: types.Message):
    conn = sqlite3.connect('db.sql')
    cur = conn.cursor()
    cur.execute(f"DELETE FROM '{str(message.from_user.id)}'")
    conn.commit()
    conn.close()


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)
