import os
import gradio as gr
import asyncio
import sys
import logging
from fastapi import FastAPI
import uvicorn
from threading import Thread

# Add the current directory to the path so we can import from app
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

# Import your main application
from main import app as fastapi_app, startup_event, generate_content, ContentRequest

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# Initialize the FastAPI app in a separate thread
def start_fastapi():
    # Don't run startup event here, as we'll run it manually
    # This prevents duplicate initialization
    uvicorn.run(fastapi_app, host="0.0.0.0", port=8080, lifespan="off")

# Start FastAPI in a separate thread
thread = Thread(target=start_fastapi, daemon=True)
thread.start()

# Run the startup event to initialize the model and index
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(startup_event())

# Define the Gradio interface
def generate(grade, subject, topic, style):
    try:
        # Create a ContentRequest object
        request = ContentRequest(
            grade=int(grade),
            subject=subject,
            topic=topic,
            style=style
        )
        
        # Call the generate_content function
        response = loop.run_until_complete(generate_content(request))
        
        return response["response"]
    except Exception as e:
        logger.error(f"Error generating content: {str(e)}")
        return f"Error: {str(e)}"

# Create the Gradio interface
with gr.Blocks(title="Swahili Content Generation") as demo:
    gr.Markdown("# Swahili Content Generation")
    gr.Markdown("Generate educational content in Swahili for primary school students.")
    
    with gr.Row():
        with gr.Column():
            grade = gr.Dropdown(
                choices=["3", "4"], 
                label="Grade Level",
                value="3"
            )
            subject = gr.Dropdown(
                choices=["math", "science"], 
                label="Subject",
                value="math"
            )
            topic = gr.Textbox(label="Topic")
            style = gr.Dropdown(
                choices=["normal", "simple", "creative"], 
                label="Style",
                value="normal"
            )
            generate_btn = gr.Button("Generate Content")
        
        with gr.Column():
            output = gr.Textbox(label="Generated Content", lines=15)
    
    generate_btn.click(
        fn=generate,
        inputs=[grade, subject, topic, style],
        outputs=output
    )

# Launch the app
if __name__ == "__main__":
    demo.launch(server_name="0.0.0.0", server_port=7860)