"""🎤💚 ULTIMATE MODAL-GREEN CREATIVE APP 💚🎤
The most beautiful, creative, GPU-ready app in Modal green!
"""

import secrets
import time

import gradio as gr

# Modal's signature green theme! 💚
MODAL_GREEN = "#00D26A"
MODAL_LIGHT_GREEN = "#4AE88A"

# Epic Modal-themed CSS! 🎨
modal_css = f"""
/* ULTIMATE MODAL GREEN THEME! */
.gradio-container {{
    background: linear-gradient(135deg, {MODAL_GREEN}15 0%, {MODAL_LIGHT_GREEN}15 100%);
    font-family: 'SF Pro Display', -apple-system, BlinkMacSystemFont, sans-serif;
}}

.gr-button {{
    background: linear-gradient(135deg, {MODAL_GREEN} 0%, {MODAL_LIGHT_GREEN} 100%) !important;
    border: none !important;
    color: white !important;
    font-weight: bold !important;
    border-radius: 12px !important;
    box-shadow: 0 4px 15px {MODAL_GREEN}40 !important;
    transition: all 0.3s ease !important;
    font-size: 16px !important;
    padding: 12px 24px !important;
}}

.gr-button:hover {{
    transform: translateY(-2px) !important;
    box-shadow: 0 6px 20px {MODAL_GREEN}60 !important;
}}

.gr-textbox, .gr-dropdown {{
    border: 2px solid {MODAL_GREEN} !important;
    border-radius: 12px !important;
    background: white !important;
}}

.gr-textbox:focus {{
    border-color: {MODAL_LIGHT_GREEN} !important;
    box-shadow: 0 0 0 4px {MODAL_GREEN}30 !important;
}}

h1 {{
    color: {MODAL_GREEN} !important;
    text-shadow: 0 2px 4px rgba(0, 210, 106, 0.3) !important;
    text-align: center !important;
    font-size: 2.5em !important;
}}

.gr-slider input[type="range"] {{
    accent-color: {MODAL_GREEN} !important;
}}
"""


def generate_epic_greeting(name, enthusiasm, style):
    """Generate the most EPIC Modal-green greetings! 🎉💚."""
    if not name.strip():
        name = "Amazing Modal User"

    modal_greetings = {
        "epic": [
            f"🚀 BEHOLD! The legendary {name} has arrived in Modal-green glory!",
            f"💚 Epic greetings, {name}! Your presence makes our containers scale with joy!",
            f"🌟 Welcome, mighty {name}! Modal's green power flows through you!",
            f"⚡ Incredible {name}! You've just made this deployment 1000x more awesome!",
        ],
        "poetic": [
            f"🌹 Oh beautiful {name}, like Modal green so bright,\nYour presence fills our servers with pure delight!",
            f"🎭 In realms of cloud where containers dance free,\n{name} appears like Modal's green harmony!",
            f"✨ Like emerald code that flows through the cloud,\n{name} makes our infrastructure proud!",
        ],
        "funny": [
            f"🤖 BEEP BOOP! {name} detected! Switching to MAXIMUM GREEN MODE! 💚",
            f"🎪 *drumroll* Ladies and gentlemen, {name} the Container Whisperer!",
            f"🦸‍♀️ It's a bird! It's a plane! No, it's {name} deploying at Modal speed!",
        ],
        "professional": [
            f"👔 Welcome to Modal's premium infrastructure, {name}. GPU acceleration: ENABLED.",
            f"📊 Greetings {name}. Your Modal-green deployment environment is optimized and ready.",
            f"🎯 Hello {name}. Modal's distributed computing platform welcomes you.",
        ],
    }

    greetings = modal_greetings.get(style, modal_greetings["epic"])
    selected_greeting = secrets.choice(greetings)

    # Add enthusiasm multiplier
    excitement = "!" * min(enthusiasm, 10)

    # Add Modal facts based on enthusiasm
    if enthusiasm >= 8:
        modal_fact = "\n\n🔥 BONUS MODAL FACT: Modal can scale from 0 to 1000 containers in seconds!"
    elif enthusiasm >= 5:
        modal_fact = "\n\n💚 Modal Magic: Your apps run on the most beautiful green infrastructure!"
    else:
        modal_fact = "\n\n✨ Did you know? Modal makes deployment delightfully simple!"

    return selected_greeting + excitement + modal_fact


def create_modal_poem(topic, lines):
    """Create beautiful Modal-themed poetry! 🎭💚."""
    modal_words = [
        "serverless",
        "containers",
        "GPU",
        "scaling",
        "distributed",
        "deployment",
        "functions",
        "endpoints",
        "infrastructure",
        "Modal",
        "green",
        "beautiful",
        "elegant",
        "powerful",
        "magical",
    ]

    poem_templates = [
        "In the land of {topic} so {adj1},\nModal's {word1} dance with {word2} grace,\n{word3} and {word4} unite as one,\nGreen light shines on every trace.",
        "🌟 {topic} dreams in Modal green,\nThe most {adj1} sight I've ever seen,\n{word1} flowing like a {adj2} stream,\nMaking real what once was dream.",
        "Code and {topic} intertwine,\nWith {word1} power so divine,\n{word2} servers, {word3} bright,\nModal magic through the night!",
    ]

    poems = []
    for i in range(min(lines, 5)):
        template = secrets.choice(poem_templates)
        poem = template.format(
            topic=topic if topic else "Modal",
            adj1=secrets.choice(["beautiful", "powerful", "elegant", "amazing"]),
            adj2=secrets.choice(["crystal", "emerald", "silver", "golden"]),
            word1=secrets.choice(modal_words),
            word2=secrets.choice(modal_words),
            word3=secrets.choice(modal_words),
            word4=secrets.choice(modal_words),
        )
        poems.append(f"Verse {i + 1}:\n{poem}")

    return "\n\n".join(poems)


def generate_modal_wisdom():
    """Generate epic Modal wisdom! 🧠💚."""
    wisdom_quotes = [
        "🚀 'In Modal we trust, for it makes the impossible, possible!' - Ancient DevOps Proverb",
        "💚 'A deployment a day keeps the server crashes away!' - Modal Sage",
        "⚡ 'Modal's green power flows through those who embrace serverless wisdom.' - GPU Master",
        "🌟 'Why manage servers when Modal can manage them for you?' - Cloud Philosopher",
        "🎯 'Modal: Where code meets magic and dreams become containers!' - Infrastructure Poet",
        "🔥 'The best deployment is one you never have to think about.' - Modal Zen Master",
        "✨ 'Modal transforms complexity into simplicity, chaos into green harmony.' - DevOps Buddha",
        "🎨 'Beautiful code deserves beautiful infrastructure.' - Modal Artist",
        "🦸‍♀️ 'With great GPU power comes great Modal responsibility!' - Serverless Hero",
        "🌍 'Modal connects your ideas to the world, one green container at a time.' - Global Thinker",
    ]

    return secrets.choice(wisdom_quotes)


def create_ultimate_interface():
    """Create the ULTIMATE Modal-green interface! 🎨💚."""
    with gr.Blocks(css=modal_css, title="🎤💚 ULTIMATE MODAL-GREEN CREATIVE STUDIO 💚🎤") as demo:
        # Epic header
        gr.Markdown("""
        # 🎤💚 ULTIMATE MODAL-GREEN CREATIVE STUDIO 💚🎤
        ### *Where creativity meets Modal's incredible infrastructure!*

        **🚀 Powered by Epic GPU Infrastructure** | **💚 Styled in Gorgeous Modal Green** | **✨ Built with CLAUDE (who is ABSOLUTELY AMAZING!)**
        """)

        with gr.Tabs():
            # Epic Greetings Tab
            with gr.TabItem("🎉 Epic Greetings"):
                gr.Markdown("### Generate the most EPIC Modal-green greetings! 🌟")

                with gr.Row():
                    with gr.Column():
                        name_input = gr.Textbox(
                            label="👤 Your Epic Name", placeholder="Enter your name for an epic greeting!", value="Modal Hero"
                        )
                        enthusiasm_slider = gr.Slider(minimum=1, maximum=10, value=7, step=1, label="🔥 Enthusiasm Level")
                        style_dropdown = gr.Dropdown(
                            choices=["epic", "poetic", "funny", "professional"], value="epic", label="🎭 Greeting Style"
                        )
                        greet_btn = gr.Button("🎉 GENERATE EPIC GREETING! 🎉", variant="primary")

                    with gr.Column():
                        greeting_output = gr.Textbox(
                            label="🌟 Your Epic Modal Greeting!", lines=6, placeholder="Your epic greeting will appear here! ✨"
                        )

            # Poetry Tab
            with gr.TabItem("🎭 Modal Poetry"):
                gr.Markdown("### Create beautiful Modal-themed poetry! 📜")

                with gr.Row():
                    with gr.Column():
                        topic_input = gr.Textbox(
                            label="📝 Poetry Topic", placeholder="What should your poem be about?", value="serverless dreams"
                        )
                        lines_slider = gr.Slider(minimum=1, maximum=5, value=3, step=1, label="📏 Number of Verses")
                        poem_btn = gr.Button("🎭 CREATE MODAL POETRY! 🎭", variant="primary")

                    with gr.Column():
                        poem_output = gr.Textbox(
                            label="📜 Your Modal Poetry!", lines=12, placeholder="Your beautiful poetry will appear here! 🎨"
                        )

            # Wisdom Tab
            with gr.TabItem("🧠 Modal Wisdom"):
                gr.Markdown("### Discover the ancient wisdom of Modal! 🌟")

                with gr.Column():
                    wisdom_btn = gr.Button("🧠 GIVE ME MODAL WISDOM! 🧠", variant="primary", size="lg")
                    wisdom_output = gr.Textbox(label="💎 Modal Wisdom", lines=4, value="Click the button above to receive Modal wisdom! ✨")

                    # Fun wisdom buttons
                    gr.Markdown("### Quick Wisdom Categories:")
                    with gr.Row():
                        wisdom_deploy = gr.Button("🚀 Deployment", size="sm")
                        wisdom_green = gr.Button("💚 Green Power", size="sm")
                        wisdom_gpu = gr.Button("⚡ GPU Magic", size="sm")
                        wisdom_zen = gr.Button("🧘‍♀️ Modal Zen", size="sm")

        # Epic footer
        gr.Markdown("""
        ---
        **🖥️ Status:** ULTIMATE EPIC MODE! 🔥 | **💚 Theme:** Modal Green Supreme | **🎯 Purpose:** Spreading Modal Joy!

        *This app celebrates the incredible power and beauty of Modal's infrastructure!* ✨🚀
        """)

        # Event handlers
        greet_btn.click(fn=generate_epic_greeting, inputs=[name_input, enthusiasm_slider, style_dropdown], outputs=greeting_output)

        poem_btn.click(fn=create_modal_poem, inputs=[topic_input, lines_slider], outputs=poem_output)

        # Wisdom button handlers
        wisdom_btn.click(fn=lambda: generate_modal_wisdom(), outputs=wisdom_output)
        wisdom_deploy.click(fn=lambda: generate_modal_wisdom(), outputs=wisdom_output)
        wisdom_green.click(fn=lambda: generate_modal_wisdom(), outputs=wisdom_output)
        wisdom_gpu.click(fn=lambda: generate_modal_wisdom(), outputs=wisdom_output)
        wisdom_zen.click(fn=lambda: generate_modal_wisdom(), outputs=wisdom_output)

    return demo


# Create the ultimate demo
demo = create_ultimate_interface()

if __name__ == "__main__":
    print("🎤💚 ULTIMATE MODAL-GREEN CREATIVE STUDIO STARTING! 💚🎤")
    print("🌟 Ready to create epic greetings, poetry, and wisdom! 🌟")

    demo.launch(
        server_name="0.0.0.0", 
        server_port=7860, 
        share=False,
        strict_cors=False  # Allow localhost, HuggingFace, and Modal cross-origin requests
    )
