import mysql.connector
import openai
import subprocess

# Configure OpenAI API with direct API key assignment
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 where target_row = 1
def process_next_row():
    connection = get_database_connection()
    cursor = connection.cursor(dictionary=True)

    # Find the next row where target_row = 1
    cursor.execute("SELECT * FROM python_chains WHERE target_row = 1 LIMIT 1")
    row = cursor.fetchone()

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

    # Get data from "do_this" table corresponding to TargetRow
    cursor.execute("SELECT * FROM do_this WHERE id = %s", (row['id'],))
    do_this_row = cursor.fetchone()

    if not do_this_row:
        print(f"No data found in 'do_this' table with id = {row['id']}.")
        cursor.close()
        connection.close()
        return

    # Get data from do_this_row and TargetRow's 'do_this' field
    do_this_data_from_table = do_this_row['do_this']
    do_this_data_from_row = row['do_this']

    # Concatenate do_this_data_from_table before do_this_data_from_row
    concatenated_data = f"{do_this_data_from_table} {do_this_data_from_row}"

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

    # Update the row with GPT's response in gpt_response_1 field
    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("2.py")

# Helper function to send data to GPT using the updated API
def send_to_gpt(input_text):
    try:
        response = openai.ChatCompletion.create(
            model="o1-preview",  # Updated to a compatible model
            messages=[{'role': 'user', 'content': input_text}]
        )
        # Return the text content of the response
        return response.choices[0].message['content'].strip()
    except Exception as e:
        return f"Error communicating with GPT: {str(e)}"

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

# Execute the function
process_next_row()
