import gradio as gr
import markdown as md
import yaml
from Agents.ContentGeneratorAgent import run_crew_cga, set_model, llm_models
from Agents.GameBuilderAgent import run_crew_game
from Agents.MarketingPostGeneratorAgent import run_crew_mpga
from Agents.TripPlannerAgent import run_crew_tp
from Agents.AIAgentDevAgent import run_crew_aida  # Import the AI Agent Dev Agent crew function
import base64

def toggle_serper_input(choice):
    return gr.Textbox(visible=(choice == "Yes"))

def update_game_instructions(example_key):
    # Load the game design examples from the YAML file
    with open('gamedesign.yaml', 'r', encoding='utf-8') as f:
        examples = yaml.safe_load(f)
    return examples.get(example_key, "")

def encode_image(image_path):
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode('utf-8')

# Encode the images
github_logo_encoded = encode_image("Images/github-logo.png")
linkedin_logo_encoded = encode_image("Images/linkedin-logo.png")
website_logo_encoded = encode_image("Images/ai-logo.png")

# UI Setup
with gr.Blocks(theme=gr.themes.Soft(font=[gr.themes.GoogleFont("Roboto Mono")]),
               css='footer {visibility: hidden}') as demo:
    gr.Markdown("# AI Agent Nexus 🤖🕵🏻")

    with gr.Tabs():
        with gr.TabItem("Intro"):
            gr.Markdown(md.description)

        # Tab for SEO Content Generator Agent
        with gr.TabItem("SEO Content Agent"):
            with gr.Accordion("📔 Description:", open=False):
                gr.Markdown(md.seo_content)
            with gr.Accordion("How to get GEMINI API KEY", open=False):
                gr.Markdown(md.gemini_api_key)
            with gr.Accordion("How to get SERPER API KEY", open=False):
                gr.Markdown(md.serper_api_key)
            with gr.Row():
                with gr.Column(scale=1):
                    model_dropdown = gr.Dropdown(
                        llm_models,
                        label="1. Select AI Model",
                        value=llm_models[0]
                    )
                    gemini_key = gr.Textbox(
                        label="2. Enter Gemini API Key",
                        type="password",
                        placeholder="Paste your Gemini API key here..."
                    )
                    search_toggle = gr.Radio(
                        ["Yes", "No"],
                        label="3. Enable Online Search?",
                        value="No"
                    )
                    serper_key = gr.Textbox(
                        label="4. Enter Serper API Key",
                        type="password",
                        visible=False,
                        placeholder="Paste your Serper API key if enabled..."
                    )
                    topic_input = gr.Textbox(
                        label="5. Enter Content Topic",
                        placeholder="Enter your article topic here..."
                    )
                    run_btn = gr.Button("Generate Content", variant="primary")
                with gr.Column(scale=3):
                    output = gr.Markdown(
                        label="Generated Content",
                        value="Your content will appear here..."
                    )
                    with gr.Accordion("Process Logs", open=True):
                        logs = gr.Markdown()

            # Event handlers for SEO Content Generator
            model_dropdown.change(set_model, model_dropdown)
            search_toggle.change(
                toggle_serper_input,
                inputs=search_toggle,
                outputs=serper_key
            )
            run_btn.click(
                run_crew_cga,
                inputs=[gemini_key, search_toggle, serper_key, topic_input],
                outputs=[output, logs],
                show_progress="full"
            )

        # Tab for Game Dev Agent
        with gr.TabItem("Game Dev Agent"):
            with gr.Accordion('📔 Description:', open=False):
                gr.Markdown(md.game_dev)
            with gr.Accordion("How to get GEMINI API KEY", open=False):
                gr.Markdown(md.gemini_api_key)
            with gr.Row():
                with gr.Column(scale=1):
                    game_model_dropdown = gr.Dropdown(
                        llm_models,
                        label="1. Select AI Model",
                        value=llm_models[0]
                    )
                    game_gemini_key = gr.Textbox(
                        label="2. Enter Gemini API Key",
                        type="password",
                        placeholder="Paste your Gemini API key here..."
                    )
                    game_example_dropdown = gr.Dropdown(
                        choices=["pacman", "pacman2", "snake", "space_invaders", "Tetris", "Frogger", "Chess", "Go", "Reversi"],
                        label="3. Select Example",
                        value="pacman"
                    )
                    game_load_example_btn = gr.Button("Load Example", variant="secondary")
                    game_instructions = gr.Textbox(
                        label="4. Enter Game Design Instructions",
                        placeholder="Enter your game design instructions here...",
                        lines=5
                    )
                    game_run_btn = gr.Button("Generate Game Code", variant="primary")
                with gr.Column(scale=3):
                    game_output = gr.Markdown(
                        label="Generated Game Code",
                        value="Your game code will appear here..."
                    )
                    with gr.Accordion("Process Logs", open=False):
                        game_logs = gr.Markdown()

            # Event handlers for Game Dev Agent
            game_model_dropdown.change(set_model, game_model_dropdown)
            game_load_example_btn.click(
                update_game_instructions,
                inputs=[game_example_dropdown],
                outputs=[game_instructions]
            )
            game_run_btn.click(
                run_crew_game,
                inputs=[game_gemini_key, game_instructions],
                outputs=[game_output, game_logs],
                show_progress="full"
            )

        # Tab for Marketing Posts Generator Agent
        with gr.TabItem("Marketing Posts Generator Agent"):
            with gr.Accordion("📔 Description: ", open=False):
                gr.Markdown(md.marking_post_gen_agent)
            with gr.Accordion("How to get GEMINI API KEY", open=False):
                gr.Markdown(md.gemini_api_key)
            with gr.Accordion("How to get SERPER API KEY", open=False):
                gr.Markdown(md.serper_api_key)
            with gr.Row():
                with gr.Column(scale=1):
                    mpga_model_dropdown = gr.Dropdown(
                        llm_models,
                        label="1. Select AI Model",
                        value=llm_models[0]
                    )
                    mpga_gemini_key = gr.Textbox(
                        label="2. Enter Gemini API Key",
                        type="password",
                        placeholder="Paste your Gemini API key here..."
                    )
                    mpga_serper_key = gr.Textbox(
                        label="3. Enter Serper API Key",
                        type="password",
                        placeholder="Paste your Serper API key here..."
                    )
                    customer_domain = gr.Textbox(
                        label="4. Enter Customer Domain",
                        placeholder="Enter the customer domain here..."
                    )
                    project_description = gr.Textbox(
                        label="5. Enter Project Description",
                        placeholder="Enter the project description here..."
                    )
                    mpga_run_btn = gr.Button("Generate Marketing Posts", variant="primary")
                with gr.Column(scale=3):
                    mpga_output = gr.Markdown(
                        label="Generated Marketing Posts",
                        value="Your marketing posts will appear here..."
                    )
                    with gr.Accordion("Process Logs", open=False):
                        mpga_logs = gr.Markdown()

            # Event handlers for Marketing Posts Generator Agent
            mpga_model_dropdown.change(set_model, mpga_model_dropdown)
            mpga_run_btn.click(
                run_crew_mpga,
                inputs=[mpga_gemini_key, customer_domain, project_description],
                outputs=[mpga_output, mpga_logs],
                show_progress="full"
            )

        # Tab for Trip Planner Agent
        with gr.TabItem("Trip Planner Agent"):
            with gr.Accordion("📔 Description: ", open=False):
                gr.Markdown(md.trip_planner_agent)
            with gr.Accordion("How to get GEMINI API KEY", open=False):
                gr.Markdown(md.gemini_api_key)
            with gr.Row():
                with gr.Column(scale=1):
                    tp_model_dropdown = gr.Dropdown(
                        llm_models,
                        label="1. Select AI Model",
                        value=llm_models[0]
                    )
                    tp_gemini_key = gr.Textbox(
                        label="2. Enter Gemini API Key",
                        type="password",
                        placeholder="Paste your Gemini API key here..."
                    )
                    origin_input = gr.Textbox(
                        label="3. Enter Origin (Your Starting Location)",
                        placeholder="Enter your origin city..."
                    )
                    cities_input = gr.Textbox(
                        label="4. Enter City Options",
                        placeholder="List the cities you're interested in visiting..."
                    )
                    trip_date_input = gr.Textbox(
                        label="5. Enter Trip Date",
                        placeholder="Enter your trip date (e.g., YYYY-MM-DD to YYYY-MM-DD)..."
                    )
                    interests_input = gr.Textbox(
                        label="6. Enter Traveler Interests",
                        placeholder="Enter your interests/hobbies..."
                    )
                    tp_run_btn = gr.Button("Generate Trip Plan", variant="primary")
                with gr.Column(scale=3):
                    tp_output = gr.Markdown(
                        label="Trip Plan",
                        value="Your trip plan will appear here..."
                    )
                    with gr.Accordion("Process Logs", open=True):
                        tp_logs = gr.Markdown()

            # Event handlers for Trip Planner Agent
            tp_model_dropdown.change(set_model, tp_model_dropdown)
            tp_run_btn.click(
                run_crew_tp,
                inputs=[tp_gemini_key, origin_input, cities_input, trip_date_input, interests_input],
                outputs=[tp_output, tp_logs],
                show_progress="full"
            )

        # Tab for AI Agent Dev Agent
        with gr.TabItem("AI Agent Dev Agent"):
            with gr.Accordion("📔 Description: ", open=False):
                gr.Markdown(md.ai_agent_dev_agent if hasattr(md, 'ai_agent_dev_agent') else
                            "This agent helps in creating new AI agents based on your query. It analyzes your requirements, designs a high-level architecture, identifies necessary agent roles and tasks, maps required tools, constructs the code, validates integration, and provides a final review and deployment plan.")
            with gr.Accordion("How to get GEMINI API KEY", open=False):
                gr.Markdown(md.gemini_api_key)
            with gr.Accordion("How to get SERPER API KEY", open=False):
                gr.Markdown(md.serper_api_key)
            with gr.Row():
                with gr.Column(scale=1):
                    aida_model_dropdown = gr.Dropdown(
                        llm_models,
                        label="1. Select AI Model",
                        value=llm_models[0]
                    )
                    aida_gemini_key = gr.Textbox(
                        label="2. Enter Gemini API Key",
                        type="password",
                        placeholder="Paste your Gemini API key here..."
                    )
                    aida_serper_key = gr.Textbox(
                        label="3. Enter Serper API Key",
                        type="password",
                        placeholder="Paste your Serper API key here..."
                    )
                    aida_agent_query = gr.Textbox(
                        label="4. Enter Agent Query",
                        placeholder="Describe the AI agent you want to create...",
                        lines=5
                    )
                    aida_run_btn = gr.Button("Generate AI Agent Blueprint", variant="primary")
                with gr.Column(scale=3):
                    aida_output = gr.Markdown(
                        label="Generated AI Agent Blueprint",
                        value="Your AI agent blueprint will appear here..."
                    )
                    with gr.Accordion("Process Logs", open=True):
                        aida_logs = gr.Markdown()

            # Event handlers for AI Agent Dev Agent
            aida_model_dropdown.change(set_model, aida_model_dropdown)
            aida_run_btn.click(
                run_crew_aida,
                inputs=[aida_gemini_key, aida_serper_key, aida_agent_query],
                outputs=[aida_output, aida_logs],
                show_progress="full"
            )

    gr.HTML(md.footer.format(github_logo_encoded, linkedin_logo_encoded, website_logo_encoded))

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