import mysql.connector
import openai
import subprocess

# Configure OpenAI API
openai.api_key = "sk-hxKXip4XIKoZSsryz4sEVPafxoT1z4MXOMZpQhX_uDT3BlbkFJebXJbeJVxqg5mZH2DyBVwvocDwjExlDJE11Nr9kMAA"  # Replace with your actual API key

# 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

    # Debugging: Print the value and type of gpt_response_2
    print(f"gpt_response_2 value: {row['gpt_response_2']} (type: {type(row['gpt_response_2'])})")

    # Check gpt_response_2 value and only proceed if it's 1
    try:
        gpt_response_2_value = int(row['gpt_response_2'])
    except (ValueError, TypeError):
        print("Script stopped: gpt_response_2 is not a valid integer.")
        cursor.close()
        connection.close()
        return

    if gpt_response_2_value != 1:
        print("Script stopped: gpt_response_2 is not equal to 1.")
        cursor.close()
        connection.close()
        return

    # Get data from "do_this" table where id = 9
    cursor.execute("SELECT do_this FROM do_this WHERE id = 9")
    do_this_row = cursor.fetchone()
    if not do_this_row:
        print("No data found in 'do_this' table with id = 9.")
        cursor.close()
        connection.close()
        return

    DoThisData = do_this_row['do_this']
    GPTResponse1Data = row['gpt_response_1']

    # Concatenate DoThisData and GPTResponse1Data with instructions
    concatenated_data = (
        "Please provide only the code without any markdown formatting or code block markers.\n"
        f"{DoThisData} {GPTResponse1Data}\n"
        "Remember, please provide only the code without any markdown formatting or code block markers."
    )

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

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

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

    # Trigger 6.py after everything is closed
    trigger_next_script("6.py")

# Helper function to send data to GPT
def send_to_gpt(input_text):
    try:
        response = openai.ChatCompletion.create(
            model="o1-preview",
            messages=[{'role': 'user', 'content': input_text}]
        )
        # Return the raw content without any filtering
        return response.choices[0].message['content']
    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)}")

# Example usage
process_next_row()
