# 🚀 Modal Deployment Script (Minimum Configuration)
# Generated by modal-for-noobs - https://github.com/arthrod/modal-for-noobs
# Deployment Mode: minimum
# Features: Basic Gradio app with dashboard and logging
# Timeout: 3600s | Scaledown: 1200s

import modal
import sys
from pathlib import Path
from datetime import datetime
from fastapi import FastAPI
import gradio as gr
from gradio.routes import mount_gradio_app
from loguru import logger

# Import dashboard components
sys.path.append(str(Path(__file__).parent))
from dashboard import create_dashboard_interface, create_dashboard_api, dashboard_state, DeploymentInfo

# 🎯 Create Modal App
app = modal.App("modal-for-noobs-ultimate_green_app")

# 🐳 Container Image Configuration (Minimum)
image = modal.Image.debian_slim(python_version="3.11").pip_install(
    "gradio",
    "fastapi[standard]",
    "uvicorn",
    "httpx",
    "markdown2"
)

# 📦 Original Application Code
"""🎤💚 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
    )


# ⚡ Modal Function Configuration
@app.function(
    image=image,
    min_containers=1,
    max_containers=1,
    timeout=3600,
    scaledown_window=1200,
)
@modal.concurrent(max_inputs=100)
@modal.asgi_app()
def deploy_gradio():
    """Deploy Gradio app with dashboard on Modal."""

    # Initialize deployment info
    deployment_info = DeploymentInfo(
        app_name="modal-for-noobs-ultimate_green_app",
        deployment_mode="minimum",
        deployment_time=datetime.now().isoformat(),
        modal_version=modal.__version__,
        python_version=f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
        gpu_enabled=False,
        timeout_seconds=3600,
        max_containers=1,
        environment={k: v for k, v in os.environ.items() if k.startswith("MODAL_")}
    )
    dashboard_state.set_deployment_info(deployment_info)

    logger.info("Starting Modal deployment in minimum mode")

    # 🔍 Detect Gradio Interface
    demo = None
    interface_names = ['demo', 'app', 'interface', 'iface']

    for name in interface_names:
        if name in globals() and hasattr(globals()[name], 'launch'):
            demo = globals()[name]
            logger.info(f"Found Gradio interface: {name}")
            break

    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
                logger.info(f"Found Gradio interface through scanning: {var_name}")
                break

    if demo is None:
        logger.error("No Gradio interface found")
        raise ValueError("Could not find Gradio interface")

    # 🎨 Create Dashboard
    dashboard = create_dashboard_interface(demo)
    dashboard.queue(max_size=10)

    # 🔗 FastAPI Setup
    fastapi_app = FastAPI(
        title="modal-for-noobs-ultimate_green_app - Modal Dashboard",
        description="Minimum deployment with monitoring dashboard",
        version="1.0.0",
        docs_url="/docs",
        redoc_url="/redoc"
    )

    # Add dashboard API endpoints
    fastapi_app = create_dashboard_api(fastapi_app)

    logger.info("Dashboard configured successfully")

    # Mount Gradio app
    return mount_gradio_app(fastapi_app, dashboard, path="/")

# Import dashboard module
import os
dashboard_content = """"""Dashboard module - embedded for deployment."""
"""Modal deployment dashboard template.

This module provides a Gradio dashboard interface for monitoring and managing
Modal deployments. It includes logging, metrics, and deployment information.
"""

import asyncio
import json
import os
import sys
from collections import deque
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, List, Optional

import gradio as gr
import modal
from fastapi import FastAPI, HTTPException
from loguru import logger
from pydantic import BaseModel

# Import Modal UI components and themes
try:
    from modal_for_noobs.ui.themes import MODAL_CSS, MODAL_THEME
except ImportError:
    # Fallback if running standalone
    MODAL_THEME = gr.themes.Soft()
    MODAL_CSS = ""


class LogEntry(BaseModel):
    """Model for log entries."""

    timestamp: str
    level: str
    message: str
    extra: dict[str, Any] | None = None


class DeploymentInfo(BaseModel):
    """Model for deployment information."""

    app_name: str
    deployment_mode: str
    deployment_time: str
    modal_version: str
    python_version: str
    gpu_enabled: bool
    timeout_seconds: int
    max_containers: int
    environment: dict[str, str]


class DashboardState:
    """Manages dashboard state and logging."""

    def __init__(self, max_logs: int = 1000):
        self.logs: deque[LogEntry] = deque(maxlen=max_logs)
        self.deployment_info: DeploymentInfo | None = None
        self.start_time = datetime.now()
        self._setup_logging()

    def _setup_logging(self):
        """Configure loguru to capture logs."""
        # Remove default handler
        logger.remove()

        # Add custom handler that stores logs in memory
        logger.add(
            self._log_handler, format="{time:YYYY-MM-DD HH:mm:ss} | {level} | {message}", level="DEBUG", backtrace=True, diagnose=True
        )

        # Also log to stdout for Modal logs
        logger.add(sys.stdout, format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level}</level> | {message}", level="INFO")

    def _log_handler(self, message):
        """Custom log handler that stores logs in memory."""
        record = message.record
        log_entry = LogEntry(
            timestamp=record["time"].strftime("%Y-%m-%d %H:%M:%S"),
            level=record["level"].name,
            message=record["message"],
            extra=record.get("extra", {}),
        )
        self.logs.append(log_entry)

    def get_logs(self, limit: int = 100) -> list[dict[str, Any]]:
        """Get the most recent logs."""
        logs_list = list(self.logs)
        if limit > 0:
            logs_list = logs_list[-limit:]
        return [log.dict() for log in logs_list]

    def get_deployment_info(self) -> dict[str, Any]:
        """Get deployment information."""
        if self.deployment_info:
            return self.deployment_info.dict()
        return {}

    def set_deployment_info(self, info: DeploymentInfo):
        """Set deployment information."""
        self.deployment_info = info
        logger.info(f"Deployment info set: {info.app_name} ({info.deployment_mode})")


# Global dashboard state
dashboard_state = DashboardState()


def create_dashboard_interface(app_demo: gr.Interface) -> gr.Blocks:
    """Create the dashboard interface with tabs for app and monitoring.

    Args:
        app_demo: The original Gradio interface/blocks to embed

    Returns:
        gr.Blocks: The complete dashboard interface
    """
    with gr.Blocks(title="Modal Deployment Dashboard", theme=MODAL_THEME, css=MODAL_CSS) as dashboard:
        gr.Markdown("# 🚀 Modal Deployment Dashboard")
        gr.Markdown("Monitor and manage your Modal deployment")

        with gr.Tabs():
            # Main App Tab
            with gr.Tab("📱 Application"):
                gr.Markdown("### Your Deployed Application")
                # Embed the original app
                if hasattr(app_demo, "render"):
                    app_demo.render()
                else:
                    gr.Markdown("⚠️ Application interface could not be rendered")

            # Logs Tab
            with gr.Tab("📋 Logs"):
                gr.Markdown("### Application Logs")

                with gr.Row():
                    log_limit = gr.Number(value=100, label="Log Limit", minimum=10, maximum=1000)
                    refresh_btn = gr.Button("🔄 Refresh Logs", variant="primary")
                    clear_btn = gr.Button("🗑️ Clear Logs", variant="secondary")

                log_output = gr.JSON(label="Recent Logs", height=600)

                def refresh_logs(limit):
                    logs = dashboard_state.get_logs(int(limit))
                    logger.info(f"Refreshed logs view (showing {len(logs)} entries)")
                    return logs

                def clear_logs():
                    dashboard_state.logs.clear()
                    logger.info("Logs cleared")
                    return []

                refresh_btn.click(refresh_logs, inputs=[log_limit], outputs=[log_output])
                clear_btn.click(clear_logs, outputs=[log_output])

                # Auto-refresh logs every 5 seconds
                dashboard.load(refresh_logs, inputs=[log_limit], outputs=[log_output])

            # Deployment Info Tab
            with gr.Tab("ℹ️ Deployment Info"):
                gr.Markdown("### Deployment Configuration")
                deployment_info = gr.JSON(label="Deployment Information", value=dashboard_state.get_deployment_info())

                refresh_info_btn = gr.Button("🔄 Refresh Info", variant="primary")

                def refresh_deployment_info():
                    info = dashboard_state.get_deployment_info()
                    logger.info("Refreshed deployment info")
                    return info

                refresh_info_btn.click(refresh_deployment_info, outputs=[deployment_info])

            # Metrics Tab
            with gr.Tab("📊 Metrics"):
                gr.Markdown("### Runtime Metrics")

                with gr.Row():
                    uptime = gr.Textbox(label="Uptime", interactive=False)
                    log_count = gr.Number(label="Total Logs", interactive=False)
                    memory_usage = gr.Textbox(label="Memory Usage", interactive=False)

                def get_metrics():
                    import psutil

                    uptime_seconds = (datetime.now() - dashboard_state.start_time).total_seconds()
                    hours, remainder = divmod(uptime_seconds, 3600)
                    minutes, seconds = divmod(remainder, 60)
                    uptime_str = f"{int(hours)}h {int(minutes)}m {int(seconds)}s"

                    process = psutil.Process()
                    memory_mb = process.memory_info().rss / 1024 / 1024

                    return uptime_str, len(dashboard_state.logs), f"{memory_mb:.2f} MB"

                metrics_btn = gr.Button("📊 Update Metrics", variant="primary")
                metrics_btn.click(get_metrics, outputs=[uptime, log_count, memory_usage])

                # Auto-refresh metrics every 10 seconds
                dashboard.load(get_metrics, outputs=[uptime, log_count, memory_usage])

        gr.Markdown("---")
        gr.Markdown("🚀 Powered by [Modal](https://modal.com) | Generated by [modal-for-noobs](https://github.com/arthrod/modal-for-noobs)")

    return dashboard


def create_dashboard_api(fastapi_app: FastAPI) -> FastAPI:
    """Add dashboard API endpoints to the FastAPI app.

    Args:
        fastapi_app: The FastAPI application instance

    Returns:
        FastAPI: The enhanced FastAPI app with dashboard endpoints
    """

    @fastapi_app.get("/api/logs")
    async def get_logs(limit: int = 100):
        """Get application logs."""
        try:
            logs = dashboard_state.get_logs(limit)
            return {"status": "success", "logs": logs, "count": len(logs)}
        except Exception as e:
            logger.error(f"Error fetching logs: {e}")
            raise HTTPException(status_code=500, detail=str(e))

    @fastapi_app.get("/api/deployment-info")
    async def get_deployment_info():
        """Get deployment information."""
        try:
            info = dashboard_state.get_deployment_info()
            return {"status": "success", "info": info}
        except Exception as e:
            logger.error(f"Error fetching deployment info: {e}")
            raise HTTPException(status_code=500, detail=str(e))

    @fastapi_app.get("/api/metrics")
    async def get_metrics():
        """Get runtime metrics."""
        try:
            import psutil

            process = psutil.Process()

            uptime_seconds = (datetime.now() - dashboard_state.start_time).total_seconds()

            metrics = {
                "uptime_seconds": uptime_seconds,
                "log_count": len(dashboard_state.logs),
                "memory_usage_mb": process.memory_info().rss / 1024 / 1024,
                "cpu_percent": process.cpu_percent(interval=0.1),
                "num_threads": process.num_threads(),
            }

            return {"status": "success", "metrics": metrics}
        except Exception as e:
            logger.error(f"Error fetching metrics: {e}")
            raise HTTPException(status_code=500, detail=str(e))

    @fastapi_app.post("/api/logs/clear")
    async def clear_logs():
        """Clear all logs."""
        try:
            dashboard_state.logs.clear()
            logger.info("Logs cleared via API")
            return {"status": "success", "message": "Logs cleared"}
        except Exception as e:
            logger.error(f"Error clearing logs: {e}")
            raise HTTPException(status_code=500, detail=str(e))

    logger.info("Dashboard API endpoints configured")
    return fastapi_app

"""

# Write dashboard module
dashboard_path = Path(__file__).parent / "dashboard.py"
if not dashboard_path.exists():
    dashboard_path.write_text(dashboard_content)

if __name__ == "__main__":
    app.run()