import mysql.connector
import openai
import subprocess
import re  # Import re module at the top

# 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 = 7
    cursor.execute("SELECT do_this FROM do_this WHERE id = 7")
    do_this_row = cursor.fetchone()
    if not do_this_row:
        print("No data found in 'do_this' table with id = 7.")
        cursor.close()
        connection.close()
        return

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

    # Concatenate DoThisData and GPTResponse1Data
    concatenated_data = f"{DoThisData} {GPTResponse1Data}"

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

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

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

    # Trigger 4.py after everything is closed
    trigger_next_script("4.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}]
        )
        # Extract the content and remove any markup
        gpt_content = response.choices[0].message['content']
        plain_text_response = strip_markup(gpt_content)
        return plain_text_response
    except Exception as e:
        return f"Error communicating with GPT: {str(e)}"

# Function to strip any markup from GPT response
import re

def strip_markup(text):
    # Remove markdown code block backticks: ```php code ``` or ```
    text = re.sub(r'```[a-z]*\n?', '', text)  # Removes the start and end backticks for code blocks
    
    # Remove inline code backticks: `code`
    text = re.sub(r'`([^`]*)`', r'\1', text)
    
    # Remove markdown links: [text](url)
    text = re.sub(r'\[([^\]]+)\]\([^)]+\)', r'\1', text)
    
    # Remove bold formatting: **text** or __text__
    text = re.sub(r'(\*\*|__)(.*?)\1', r'\2', text)
    
    # Remove italic formatting: *text* or _text_
    text = re.sub(r'(\*|_)(.*?)\1', r'\2', text)
    
    # Remove strikethrough: ~~text~~
    text = re.sub(r'~~(.*?)~~', r'\1', text)
    
    text = re.sub(r'<[^>]+>', '', text)
    
    # Remove images: ![alt text](image_url)
    text = re.sub(r'!\[.*?\]\(.*?\)', '', text)
    
    return text.strip()


# 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()
