# Dockerfile — Multi-stage build for a Python application.
#
# Navigate: SPC s i (imenu), Lint: flycheck (hadolint)
# Build:    SPC m b (podman build), Run: SPC m r (podman run)
#
# Build:  podman build -t myapp:latest -f Dockerfile .
# Run:    podman run --rm -p 8080:8080 myapp:latest

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

WORKDIR /build

# Install dependencies first (layer caching)
COPY requirements.txt .
RUN pip install --no-cache-dir --prefix=/install -r requirements.txt

# --- Stage 2: Runtime image ---
FROM python:3.12-slim AS runtime

# Security: non-root user
RUN groupadd -r appuser && useradd -r -g appuser -d /app -s /sbin/nologin appuser

WORKDIR /app

# Copy installed packages from builder
COPY --from=builder /install /usr/local

# Copy application code
COPY app/ ./app/
COPY main.py .

# Set ownership
RUN chown -R appuser:appuser /app

USER appuser

EXPOSE 8080

# Healthcheck: verify the app responds
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
  CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8080/health')" || exit 1

ENTRYPOINT ["python", "main.py"]
