FROM python:3.10-slim AS builder

# Builder stage: install dependencies and prepare app files (including bytecode compilation).

WORKDIR /app

COPY requirements.txt .
 
# Install into a separate prefix (/install) so we can copy into the runtime image without pip cache.
RUN pip install --no-cache-dir --prefix=/install -r requirements.txt \
	&& pip install --no-cache-dir --prefix=/install gunicorn

COPY . .

# Compile to .pyc and remove source files (.py) so the runtime image contains no app source.
RUN python -m compileall -b . \
	&& find . -type f -name "*.py" -delete \
	&& rm -rf tests __pycache__


FROM python:3.10-slim

# Runtime stage: only runtime + prepared files (no .py source code from the app).

ENV PYTHONUNBUFFERED=1
WORKDIR /app

COPY --from=builder /install /usr/local
COPY --from=builder /app /app

EXPOSE 8000
CMD ["gunicorn", "--bind", "0.0.0.0:8000", "app:app"]