import os
import openai
import gradio as gr
from dotenv import load_dotenv

# Load API key from .env file
load_dotenv()
api_key = os.getenv("openai")

if not api_key:
    raise ValueError("API Key not found! Ensure you have set 'OPENAI_API_KEY' in your .env file.")

# Set up OpenAI API Key
openai.api_key = api_key

# Define chatbot function
def python_tutor_bot(user_input):
    if not user_input.strip():
        return "Please enter a valid question."
    
    try:
        response = openai.ChatCompletion.create(
            model="gpt-4-turbo",  # Corrected model name
            messages=[
                {
                    "role": "system",
                    "content": (
                        "You are a Python tutor bot designed to help beginners learn and troubleshoot Python programming. "
                        "Explain concepts in simple terms, provide clear examples, and help debug user code.\n\n"
                        "### Guidelines:\n"
                        "- Use beginner-friendly language, as if explaining to an 8th grader.\n"
                        "- Offer simple code examples to illustrate concepts.\n"
                        "- Identify and fix errors in user-provided code with explanations.\n"
                        "- Encourage follow-up questions to ensure understanding.\n"
                    ),
                },
                {"role": "user", "content": user_input}
            ],
            temperature=0.1,
            max_tokens=1000,
            top_p=0.9,
            frequency_penalty=0,
            presence_penalty=0.3
        )
        return response["choices"][0]["message"]["content"]
    
    except openai.error.OpenAIError as e:
        return f"Error: {str(e)}"

# Create Gradio chat interface
chatbot_ui = gr.Interface(
    fn=python_tutor_bot,
    inputs=gr.Textbox(lines=3, placeholder="Ask me anything about Python..."),
    outputs=gr.Textbox(),
    title="Python Tutor Bot for beginners",
    description="A friendly Python tutor bot to help you learn and troubleshoot Python. Ask any question!"
)

# Launch Gradio UI
if __name__ == "__main__":
    chatbot_ui.launch()