import sys
import mysql.connector
import requests

#########################################################################

# DB
def db_connect():
    conn = mysql.connector.connect(
        host="{HOST}",
        user="{USER}",
        password="{PASSWORD}",
        database="{DB_NAME}"
    )
    return conn

def db_update(conn, a_id, a_answer):
    cursor = conn.cursor()
    a_answer = a_answer.replace ("'", "\'")
    a_answer = a_answer.replace ('"', ' ')    
    sql='update idioms set resp_2="'+a_answer+'" where id ="'+str(a_id)+'" '
    cursor.execute(sql)
    conn.commit()

def db_close (conn):
    conn.close()

######################################################################

def ask_openai (q):
  url = "https://api.openai.com/v1/chat/completions"
  headers = {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer {TOKEN}',
    'OpenAI-Organization': '{ORG_ID}' 
  }
  data = {
    "model": "gpt-3.5-turbo",
    "messages": [
      {
        "role": "user",
        "content": "Explain the meaning of the following expression in a very sort form: "+q
      }
    ]
  }
  #print(f"requesting: {data}")
  a=""
  response = requests.post(url, headers=headers, json=data)
  response_json = response.json()
  if response.status_code == 200:
     
    choices = response_json["choices"]
    a = choices[0]["message"]["content"]
    print (f"answer: {a}\n")
  else:
    print(f"Error: {response.status_code}\n")
  if (a==""):
    print(response_json)
  return a
  
#########################################################################

conn=db_connect()
mycursor = conn.cursor(dictionary=True)
mycursor.execute("SELECT * FROM idioms where resp_2= '' order by id asc limit 15")
myresult = mycursor.fetchall()
for item in myresult:
  print(str(item["id"])+" "+item["text"]+" = "+ item["rephrase"])
  answer  = ask_openai (item["rephrase"])
  if (answer !="" ):
     db_update(conn, item["id"], answer)
  else:
     break

db_close (conn)

#########################################################################




