"""Minimum deployment template for Modal.

This template provides basic Gradio deployment with dashboard and logging support.
"""

TEMPLATE = '''# 🚀 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: {timeout_seconds}s | Scaledown: {scaledown_window}s

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("{app_name}")

# 🐳 Container Image Configuration (Minimum)
{image_config}

# 📦 Original Application Code
{original_code}

# ⚡ Modal Function Configuration
@app.function(
    image=image,
    min_containers=1,
    max_containers=1,
    timeout={timeout_seconds},
    scaledown_window={scaledown_window},
)
@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="{app_name}",
        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={timeout_seconds},
        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="{app_name} - 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
import base64

# Dashboard module content (base64 encoded to avoid quote conflicts)
dashboard_module_encoded = "{dashboard_module_b64}"
dashboard_module_code = base64.b64decode(dashboard_module_encoded).decode('utf-8')

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

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