# Multi-stage Dockerfile for Python applications
# Generated by AIWG deploy-gen
# Research: REF-001 BP-8 - Containerized Deployment

# =============================================================================
# Stage 1: Build
# =============================================================================
FROM python:{{PYTHON_VERSION}}-slim AS builder

WORKDIR /app

# Install build dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
    build-essential \
    && rm -rf /var/lib/apt/lists/*

# Create virtual environment
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"

# Copy requirements
COPY requirements*.txt ./
COPY pyproject.toml* ./
COPY setup.py* ./
COPY setup.cfg* ./

# Install dependencies
RUN \
  if [ -f requirements.txt ]; then pip install --no-cache-dir -r requirements.txt; \
  elif [ -f pyproject.toml ]; then pip install --no-cache-dir .; \
  elif [ -f setup.py ]; then pip install --no-cache-dir .; \
  fi

# =============================================================================
# Stage 2: Production
# =============================================================================
FROM python:{{PYTHON_VERSION}}-slim AS runner

WORKDIR /app

# Set production environment
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
ENV PORT={{PORT}}

# Create non-root user
RUN groupadd --system --gid 1001 appgroup && \
    useradd --system --uid 1001 --gid appgroup appuser

# Copy virtual environment from builder
COPY --from=builder /opt/venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"

# Copy application code
COPY --chown=appuser:appgroup . .

# Switch to non-root user
USER appuser

# Expose port
EXPOSE {{PORT}}

# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:{{PORT}}/health')" || exit 1

# Start application
CMD ["python", "{{ENTRY_POINT}}"]
