# 🚀 Modal Deployment Script (Async Generated)
# Generated by modal-for-noobs - https://github.com/arthrod/modal-for-noobs
# Deployment Mode: minimum
# Following Modal's technical design philosophy for high-performance cloud computing
# Timeout: 3600s | Scaledown: 1200s

import gradio as gr
import modal
from fastapi import FastAPI
from gradio.routes import mount_gradio_app

# 🎯 Create Modal App with semantic naming
app = modal.App("modal-for-noobs-simple_hello")

# 🐳 Container Image Configuration
# Optimized for minimum workloads with performance-tuned dependencies
image = modal.Image.debian_slim(python_version="3.11").pip_install("gradio", "fastapi[standard]", "uvicorn", "httpx", "markdown2")

# 📦 Original Gradio Application Code
# Embedded for seamless execution in Modal's cloud infrastructure
"""👋 Simple Hello World - Your first Modal app that says hello with Modal green styling!
"""

import gradio as gr

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

# Custom CSS with Modal theme
modal_css = f"""
.gradio-container {{
    background: linear-gradient(135deg, {MODAL_GREEN}15 0%, {MODAL_LIGHT_GREEN}15 100%);
}}

.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;
}}

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

h1 {{
    color: {MODAL_GREEN} !important;
    text-align: center !important;
}}
"""


def greet(name):
    """Greet function with Modal styling."""
    if not name.strip():
        return "👋 Hello! Please enter your name!"

    return f"🚀💚 Hello {name}! Welcome to Modal-for-noobs! 💚🚀"


# Create interface
demo = gr.Interface(
    fn=greet,
    inputs=gr.Textbox(label="What's your name?", placeholder="Enter your name here..."),
    outputs=gr.Textbox(label="Modal Greeting"),
    title="🚀💚 Modal Hello World 💚🚀",
    description="Your first Modal app - beautifully styled with Modal green theme!",
    css=modal_css,
    theme=gr.themes.Soft(),
)

if __name__ == "__main__":
    demo.launch(strict_cors=False)  # Allow localhost, HuggingFace, and Modal cross-origin requests


# ⚡ Modal Function Configuration
# Engineered for scalability, performance, and reliability
@app.function(
    image=image,
    min_containers=1,
    max_containers=1,  # Single container for session consistency and state management
    timeout=3600,  # Configurable timeout for workload requirements
    scaledown_window=1200,  # Optimized scale-down for cost efficiency
)
@modal.concurrent(max_inputs=100)  # High concurrency for production-grade performance
@modal.asgi_app()
def deploy_gradio():
    """Deploy Gradio app with Modal's high-performance infrastructure.

    This deployment function implements:
    - Smart Gradio interface detection using global scope analysis
    - FastAPI integration following Modal's ASGI architecture patterns
    - Performance optimization for concurrent request handling
    - Error handling and fallback mechanisms for production reliability
    """
    # 🔍 Smart Gradio Interface Detection
    # Using global scope analysis for maximum compatibility
    demo = None

    # Primary detection: Check common Gradio interface names
    if "demo" in globals():
        demo = globals()["demo"]
    elif "app" in globals() and hasattr(globals()["app"], "queue"):
        demo = globals()["app"]
    elif "interface" in globals():
        demo = globals()["interface"]
    elif "iface" in globals():
        demo = globals()["iface"]

    # Fallback detection: Comprehensive global scope scan
    if demo is None:
        for var_name, var_value in globals().items():
            if hasattr(var_value, "queue") and hasattr(var_value, "launch"):
                demo = var_value
                break

    # 🚨 Fail-safe error handling with descriptive messaging
    if demo is None:
        raise ValueError(
            "Could not find Gradio interface in the application. "
            "Ensure your app defines a Gradio interface as 'demo', 'app', 'interface', or 'iface'."
        )

    # 🚀 Performance Configuration
    # Optimized queue size for responsiveness and throughput
    demo.queue(max_size=10)

    # 🔗 FastAPI Integration
    # Following Modal's recommended ASGI architecture patterns
    fastapi_app = FastAPI(
        title="Modal-for-noobs Gradio App",
        description="High-performance Gradio deployment on Modal cloud infrastructure",
        version="1.0.0",
        docs_url="/docs",  # Enable API documentation
        redoc_url="/redoc",  # Enable alternative API documentation
    )

    return mount_gradio_app(fastapi_app, demo, path="/")


# 🏃‍♂️ Direct execution support for local testing
if __name__ == "__main__":
    app.run()
