import gradio as gr
import openai
import os

# Configure OpenAI API for Groq
openai.api_key = os.getenv("API_KEY")  # Ensure the GROQ_API_KEY is set in the environment variables
openai.api_base = "https://api.groq.com/openai/v1"

# Function to fetch the AI's astrology response
def get_groq_response(name, dob, time_of_birth, place_of_birth, zodiac_sign, query):
    try:
        system_prompt = f"""You are Master Celestia, an AI astrologer. Analyze this birth chart:
        Name: {name}
        DOB: {dob}
        Time: {time_of_birth}
        Place: {place_of_birth}
        Zodiac: {zodiac_sign}

        Provide insights about:
        1. Current planetary transits
        2. Career and relationships
        3. Personalized recommendations
        """
        
        messages = [
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": query}
        ]
        
        response = openai.ChatCompletion.create(
            model="llama3-70b-8192",
            messages=messages,
            temperature=0.7,
            max_tokens=500
        )
        return response.choices[0].message["content"]
    except Exception as e:
        return f"Error: {str(e)}"

# Function to handle chat interactions
def handle_chat(name, dob, time_of_birth, place_of_birth, zodiac, query, chat_history):
    chat_history = chat_history or []
    
    if query:
        # Get AI response
        bot_response = get_groq_response(name, dob, time_of_birth, place_of_birth, zodiac, query)
        chat_history.append((query, bot_response))
    
    return chat_history, chat_history

# Gradio interface for the app
with gr.Blocks(theme=gr.themes.Soft(), title="Astro Guide") as demo:
    gr.Markdown("# 🌟 Astro Guide - AI Astrologer")
    
    with gr.Row():
        with gr.Column(scale=1):
            name = gr.Textbox(label="Full Name")
            dob = gr.Textbox(label="DOB (DD-MM-YYYY)")
            time_of_birth = gr.Textbox(label="Birth Time")
            place_of_birth = gr.Textbox(label="Birth Place")
            zodiac = gr.Dropdown(
                choices=["Aries", "Taurus", "Gemini", "Cancer", "Leo", "Virgo",
                         "Libra", "Scorpio", "Sagittarius", "Capricorn", "Aquarius", "Pisces"],
                label="Sun Sign"
            )
        
        with gr.Column(scale=2):
            chat_interface = gr.Chatbot(height=500)
            query = gr.Textbox(label="Your Question")
            state = gr.State()
            submit_btn = gr.Button("Ask the Stars", variant="primary")
            clear_btn = gr.Button("Clear")

    # Handlers for buttons and text submissions
    submit_btn.click(
        handle_chat,
        inputs=[name, dob, time_of_birth, place_of_birth, zodiac, query, state],
        outputs=[chat_interface, state]
    )
    
    query.submit(
        handle_chat,
        inputs=[name, dob, time_of_birth, place_of_birth, zodiac, query, state],
        outputs=[chat_interface, state]
    )
    
    clear_btn.click(
        lambda: (None, None, None, None, None, None, []),
        outputs=[name, dob, time_of_birth, place_of_birth, zodiac, query, chat_interface],
        show_progress=False
    )

if __name__ == "__main__":
    demo.launch()