# =============================================================================
# Dockerfile for Django Backend with Uvicorn
# =============================================================================
# Usage:
#   Development: WORKERS=1 RELOAD=--reload (source mounted, hot reload)
#   Production:  WORKERS=4 RELOAD="" (no reload, multiple workers)

# =============================================================================
# Stage 1: Base with system dependencies
# =============================================================================
FROM python:3.11-slim AS base

ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1

WORKDIR /app

# Install system dependencies (cached layer)
RUN apt-get update && apt-get install -y --no-install-recommends \
    build-essential \
    libpq-dev \
    gdal-bin \
    libgdal-dev \
    libgeos-dev \
    libproj-dev \
    postgresql-client \
    # WeasyPrint dependencies (for django-afip PDF generation)
    libglib2.0-0 \
    libpango-1.0-0 \
    libpangocairo-1.0-0 \
    libgdk-pixbuf-2.0-0 \
    libffi-dev \
    libcairo2 \
    libgirepository1.0-dev \
    gir1.2-pango-1.0 \
    fonts-dejavu-core \
    && rm -rf /var/lib/apt/lists/*

# =============================================================================
# Stage 2: Dependencies (cached layer)
# =============================================================================
FROM base AS deps

# Copy only requirements for dependency installation
COPY requirements.txt .

# Install Python dependencies
RUN pip install --no-cache-dir -r requirements.txt

# =============================================================================
# Stage 3: Runtime (uvicorn with configurable workers)
# =============================================================================
FROM base AS runtime

# Copy dependencies from deps stage
COPY --from=deps /usr/local/lib/python3.11/site-packages /usr/local/lib/python3.11/site-packages
COPY --from=deps /usr/local/bin /usr/local/bin

# Copy requirements (for reference)
COPY requirements.txt .

# Create directories
RUN mkdir -p /var/etc/static /app/media

# Note: Source code mounted at runtime for dev, copied for prod
EXPOSE 8000

# Uvicorn with configurable workers and reload
# Dev:  WORKERS=1 RELOAD=--reload
# Prod: WORKERS=4 RELOAD=""
CMD uvicorn amar_django_back.asgi:application --host 0.0.0.0 --port 8000 --workers ${WORKERS:-1} ${RELOAD}
