import MySQLdb
from openai import OpenAI
import os
import logging  # ✅ Proper import at the top

logging.info(f"OPENAI_API_KEY is: {os.getenv('OPENAI_API_KEY')}")

logging.basicConfig(level=logging.INFO)  # ✅ Proper config at module level

# openai.api_key = os.getenv("OPENAI_API_KEY")  # or set it statically

# ✅ Instantiate the client
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))  


def call_openai_prompt(prompt_id, user_input):
    try:
        #db_password = os.getenv("DB_PASSWORD")
        #if not db_password:
        #    raise EnvironmentError("DB_PASSWORD environment variable not set.")

        conn = MySQLdb.connect(
            host="localhost",
            user="openai_user",
            passwd="IOyg76H2l%252BewRX2xhsDJAo7qnfVDHtx9RB%253D%",
            #passwd=db_password,
            db="openai_prompts",
            #db="openai_prompts",
            charset="utf8mb4"
        )
        cursor = conn.cursor()

        cursor.execute("""
            SELECT role, content FROM prompt_messages
            WHERE prompt_id = %s ORDER BY sequence
        """, (prompt_id,))
        rows = cursor.fetchall()
        if not rows:
            return "Prompt not found or has no messages."

        messages = []
        for role, content in rows:
            filled = content.replace("{user_input}", user_input)
            messages.append({"role": role, "content": filled})

        response = client.chat.completions.create(
            model="gpt-4",
            messages=messages
        )
        return response.choices[0].message.content

    except Exception as e:
        logging.error(f"OpenAI or DB error: {e}")
        return "Error generating response."
