import mysql.connector
import openai

# Configure OpenAI API
openai.api_key = "sk-hxKXip4XIKoZSsryz4sEVPafxoT1z4MXOMZpQhX_uDT3BlbkFJebXJbeJVxqg5mZH2DyBVwvocDwjExlDJE11Nr9kMAA"

# Database connection
def get_database_connection():
    return mysql.connector.connect(
        host='localhost',
        user='root',
        password='',
        database='gpt_o1_preview'
    )

# Function to process the next row with a blank gpt_response_2
def process_next_row():
    connection = get_database_connection()
    cursor = connection.cursor(dictionary=True)

    # Find the next row where gpt_response_2 is NULL or empty
    cursor.execute("SELECT * FROM python_chains WHERE gpt_response_2 IS NULL OR gpt_response_2 = '' LIMIT 1")
    row = cursor.fetchone()

    # If no such row exists, return
    if not row:
        print("No rows with blank gpt_response_2.")
        cursor.close()
        connection.close()
        return

    # Concatenate "what do you think about this joke" with gpt_response_1
    concatenated_data = f"what do you think about this joke {row['gpt_response_1']}"

    # Send the concatenated data to GPT
    gpt_response = send_to_gpt(concatenated_data)

    # Update the row with GPT's response in gpt_response_2
    cursor.execute("UPDATE python_chains SET gpt_response_2 = %s WHERE id = %s", (gpt_response, row['id']))
    connection.commit()

    cursor.close()
    connection.close()
    print("GPT response stored in gpt_response_2 for row ID:", row['id'])

# Helper function to send data to GPT
def send_to_gpt(input_text):
    try:
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=[{'role': 'user', 'content': input_text}]
        )
        return response.choices[0].message['content']
    except Exception as e:
        return f"Error communicating with GPT: {str(e)}"

# Example usage
process_next_row()
