"""Marimo deployment template for Modal.

This template provides Gradio deployment with Marimo notebook integration.
Uses safe template constants to avoid f-string conflicts.
"""

from modal_for_noobs.templates.template_constants import (
    APP_EXECUTION,
    DASHBOARD_IMPORTS,
    DASHBOARD_MODULE_TEMPLATE,
    GPU_DETECTION,
    GRADIO_DETECTION,
    MARIMO_DASHBOARD_TAB,
    MARIMO_NOTEBOOK_FOOTER,
    MARIMO_NOTEBOOK_HEADER,
    MARIMO_NOTEBOOK_WELCOME,
    MARIMO_PROXY_ENDPOINTS,
    MARIMO_SERVER_FUNCTION,
    MODAL_IMPORTS,
)


def create_marimo_template(app_name: str, image_config: str, original_code: str,
                          timeout_seconds: int = 300, max_containers: int = 1) -> str:
    """Create marimo template using safe constants."""
    # Header
    return f"""# 🚀 Modal Deployment Script (Marimo Configuration)
# Generated by modal-for-noobs - https://github.com/arthrod/modal-for-noobs
# Deployment Mode: marimo
# Features: Gradio app with Marimo notebooks, ML libraries, dashboard, and logging
# Timeout: {timeout_seconds}s

{MODAL_IMPORTS}

{DASHBOARD_IMPORTS}

# Configuration constants
APP_NAME = "{app_name}"
APP_TITLE = "{app_name} - Modal Dashboard (Marimo)"
APP_DESCRIPTION = "Optimized deployment with Marimo notebooks and monitoring"
DEPLOYMENT_MODE = "marimo"
TIMEOUT_SECONDS = {timeout_seconds}
MAX_CONTAINERS = {max_containers}

# Create Modal App
app = modal.App(APP_NAME)

# Container Image Configuration (Marimo + ML)
{image_config}

# Original Application Code
{original_code}

# Marimo notebook constants
MARIMO_NOTEBOOK_HEADER = '''{MARIMO_NOTEBOOK_HEADER}'''
MARIMO_NOTEBOOK_WELCOME = '''{MARIMO_NOTEBOOK_WELCOME}'''
MARIMO_NOTEBOOK_FOOTER = '''{MARIMO_NOTEBOOK_FOOTER}'''

{MARIMO_SERVER_FUNCTION}

# Modal Function Configuration with GPU
@app.function(
    image=image,
    gpu="any",  # GPU support for ML workloads
    min_containers=1,
    max_containers={max_containers},
    timeout={timeout_seconds},
    memory=16384,  # 16GB RAM
)
@modal.concurrent(max_inputs=100)
@modal.asgi_app()
def deploy_gradio():
    \"\"\"Deploy Gradio app with Marimo notebooks and dashboard on Modal.\"\"\"

    {GPU_DETECTION}

    # Initialize deployment info with Marimo specifics
    deployment_info = DeploymentInfo(
        app_name=APP_NAME,
        deployment_mode=DEPLOYMENT_MODE,
        deployment_time=datetime.now().isoformat(),
        modal_version=modal.__version__,
        python_version=str(sys.version_info.major) + "." + str(sys.version_info.minor) + "." + str(sys.version_info.micro),
        gpu_enabled=gpu_available,
        timeout_seconds=TIMEOUT_SECONDS,
        max_containers=MAX_CONTAINERS,
        environment={{
            **{{k: v for k, v in os.environ.items() if k.startswith("MODAL_")}},
            "GPU_AVAILABLE": str(gpu_available),
            "GPU_NAME": gpu_name,
            "MARIMO_ENABLED": "true",
            "MARIMO_PORT": "2718",
        }}
    )
    dashboard_state.set_deployment_info(deployment_info)

    logger.info("Starting Modal deployment in marimo mode (GPU: " + str(gpu_available) + ")")

    # Start Marimo in the background
    asyncio.create_task(start_marimo_server())

    {GRADIO_DETECTION}

    # Create Dashboard with Marimo integration
    with gr.Blocks() as enhanced_dashboard:
        gr.Markdown("# 🚀 Modal Deployment Dashboard")
        gr.Markdown("Monitor and manage your Modal deployment with Marimo notebook integration")

        with gr.Tabs():
            {MARIMO_DASHBOARD_TAB}

            # Original dashboard tabs
            dashboard_interface = create_dashboard_interface(demo)
            for tab in dashboard_interface.children:
                if hasattr(tab, 'children'):
                    for child in tab.children:
                        child.render()

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

    enhanced_dashboard.queue(max_size=20)

    # FastAPI Setup with Marimo proxy
    fastapi_app = FastAPI(
        title=APP_TITLE,
        description=APP_DESCRIPTION,
        version="1.0.0",
        docs_url="/docs",
        redoc_url="/redoc"
    )

    {MARIMO_PROXY_ENDPOINTS}

    # Add dashboard API endpoints
    fastapi_app = create_dashboard_api(fastapi_app)

    logger.info("Dashboard with Marimo integration configured successfully")

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

# Dashboard module creation
dashboard_content = '''{DASHBOARD_MODULE_TEMPLATE}'''

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

{APP_EXECUTION}
"""


# Legacy TEMPLATE variable for compatibility
TEMPLATE = '''# 🚀 Modal Deployment Script (Marimo Configuration)
# Generated by modal-for-noobs - https://github.com/arthrod/modal-for-noobs
# Deployment Mode: marimo
# Features: Gradio app with Marimo notebooks, ML libraries, dashboard, and logging
# Timeout: {timeout_seconds}s

{MODAL_IMPORTS}

{DASHBOARD_IMPORTS}

# Configuration constants
APP_NAME = "{app_name}"
APP_TITLE = "{app_name} - Modal Dashboard (Marimo)"
APP_DESCRIPTION = "Optimized deployment with Marimo notebooks and monitoring"
DEPLOYMENT_MODE = "marimo"
TIMEOUT_SECONDS = {timeout_seconds}
MAX_CONTAINERS = {max_containers}

# Create Modal App
app = modal.App(APP_NAME)

# Container Image Configuration (Marimo + ML)
{image_config}

# Original Application Code
{original_code}

# Use the template constants defined above
{MARIMO_SERVER_FUNCTION}

# Modal Function Configuration with GPU
@app.function(
    image=image,
    gpu="any",  # GPU support for ML workloads
    min_containers=1,
    max_containers={max_containers},
    timeout={timeout_seconds},
    memory=16384,  # 16GB RAM
)
@modal.concurrent(max_inputs=100)
@modal.asgi_app()
def deploy_gradio():
    """Deploy Gradio app with Marimo notebooks and dashboard on Modal."""

    {GPU_DETECTION}

    # Initialize deployment info with Marimo specifics
    deployment_info = DeploymentInfo(
        app_name=APP_NAME,
        deployment_mode=DEPLOYMENT_MODE,
        deployment_time=datetime.now().isoformat(),
        modal_version=modal.__version__,
        python_version=str(sys.version_info.major) + "." + str(sys.version_info.minor) + "." + str(sys.version_info.micro),
        gpu_enabled=gpu_available,
        timeout_seconds=TIMEOUT_SECONDS,
        max_containers=MAX_CONTAINERS,
        environment={{
            **{{k: v for k, v in os.environ.items() if k.startswith("MODAL_")}},
            "GPU_AVAILABLE": str(gpu_available),
            "GPU_NAME": gpu_name,
            "MARIMO_ENABLED": "true",
            "MARIMO_PORT": "2718",
        }}
    )
    dashboard_state.set_deployment_info(deployment_info)

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

    # Start Marimo in the background
    asyncio.create_task(start_marimo_server())

    {GRADIO_DETECTION}

    # Create Dashboard with Marimo integration
    with gr.Blocks() as enhanced_dashboard:
        gr.Markdown("# 🚀 Modal Deployment Dashboard")
        gr.Markdown("Monitor and manage your Modal deployment with Marimo notebook integration")

        with gr.Tabs():
            {MARIMO_DASHBOARD_TAB}

            # Original dashboard tabs
            dashboard_interface = create_dashboard_interface(demo)
            for tab in dashboard_interface.children:
                if hasattr(tab, 'children'):
                    for child in tab.children:
                        child.render()

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

    enhanced_dashboard.queue(max_size=20)

    # FastAPI Setup with Marimo proxy
    fastapi_app = FastAPI(
        title=APP_TITLE,
        description=APP_DESCRIPTION,
        version="1.0.0",
        docs_url="/docs",
        redoc_url="/redoc"
    )

    {MARIMO_PROXY_ENDPOINTS}

    # Add dashboard API endpoints
    fastapi_app = create_dashboard_api(fastapi_app)

    logger.info("Dashboard with Marimo integration configured successfully")

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

# Dashboard module creation
dashboard_content = """{DASHBOARD_MODULE_TEMPLATE}"""

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

{APP_EXECUTION}
'''
