import mysql.connector
import openai
import subprocess

# 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_1
def process_next_row():
    connection = get_database_connection()
    cursor = connection.cursor(dictionary=True)

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

    # If no such row exists, return
    if not row:
        print("No rows with blank gpt_response_1.")
        cursor.close()
        connection.close()
        trigger_next_script()  # Trigger 2.py after everything is closed
        return

    # Concatenate do_this and to_this fields
    concatenated_data = f"{row['do_this']} {row['to_this']}"

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

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

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

    # Trigger 2.py after everything is closed
    trigger_next_script()

# 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)}"

# Function to trigger the execution of 2.py
def trigger_next_script():
    try:
        subprocess.run(["python", "2.py"], check=True)
        print("2.py has been triggered successfully.")
    except Exception as e:
        print(f"Failed to trigger 2.py: {str(e)}")

# Example usage
process_next_row()
