"""Mapanare deploy scaffolding -- generates Dockerfile + docker-compose.yml."""

from __future__ import annotations

import os

DOCKERFILE_TEMPLATE = """\
# Mapanare agent application -- multi-stage build
# Generated by: mapanare deploy

# Stage 1: Build
FROM python:3.12-slim AS builder

WORKDIR /app

# Install Mapanare compiler
RUN pip install --no-cache-dir mapanare

# Copy source files
COPY . .

# Compile the application
RUN mapanare compile {entry_point} -o app.py

# Stage 2: Runtime
FROM python:3.12-slim

WORKDIR /app

# Install runtime dependencies only
RUN pip install --no-cache-dir mapanare

# Copy compiled output
COPY --from=builder /app/app.py .
COPY --from=builder /app/*.mn ./

# Health check endpoint
HEALTHCHECK --interval=10s --timeout=3s --start-period=5s \\
    --retries=3 CMD curl -f http://localhost:8080/health || exit 1

EXPOSE 8080

CMD ["python", "app.py"]
"""

DOCKER_COMPOSE_TEMPLATE = """\
# Mapanare agent application -- docker-compose
# Generated by: mapanare deploy

services:
  app:
    build: .
    ports:
      - "8080:8080"
    environment:
      - MAPANARE_HEALTH_PORT=8080
    restart: unless-stopped
    healthcheck:
      test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8080/health')"]
      interval: 10s
      timeout: 3s
      start_period: 5s
      retries: 3
"""

DOCKERIGNORE_TEMPLATE = """\
# Mapanare deploy -- .dockerignore
__pycache__/
*.pyc
.git/
.env
.venv/
*.egg-info/
dist/
build/
"""


def scaffold_deploy(
    project_dir: str,
    entry_point: str = "main.mn",
) -> list[str]:
    """Generate deployment files in the project directory.

    Returns list of created file paths.
    """
    created: list[str] = []

    dockerfile_path = os.path.join(project_dir, "Dockerfile")
    if not os.path.exists(dockerfile_path):
        with open(dockerfile_path, "w", encoding="utf-8") as f:
            f.write(DOCKERFILE_TEMPLATE.format(entry_point=entry_point))
        created.append(dockerfile_path)

    compose_path = os.path.join(project_dir, "docker-compose.yml")
    if not os.path.exists(compose_path):
        with open(compose_path, "w", encoding="utf-8") as f:
            f.write(DOCKER_COMPOSE_TEMPLATE)
        created.append(compose_path)

    dockerignore_path = os.path.join(project_dir, ".dockerignore")
    if not os.path.exists(dockerignore_path):
        with open(dockerignore_path, "w", encoding="utf-8") as f:
            f.write(DOCKERIGNORE_TEMPLATE)
        created.append(dockerignore_path)

    return created
