FROM python:3.13-slim-bookworm

# If the service expects a different port, provide it here (f.e Render expects port 10000)
ARG PORT=8080
# Only set for local/direct access. When TLS is used, the API_URL is assumed to be the same as the frontend.
ARG API_URL
ENV PORT=$PORT REFLEX_API_URL=${API_URL:-http://localhost:$PORT} REFLEX_REDIS_URL=redis://localhost PYTHONUNBUFFERED=1

ENV REFLEX_USE_GRANIAN=False

# Install Caddy and redis server inside image
RUN apt-get update -y
RUN apt-get install -y libgl1 libglib2.0-0 poppler-utils tesseract-ocr unzip curl caddy redis-server procps
RUN rm -rf /var/lib/apt/lists/*

WORKDIR /app

COPY requirements.txt .

# Install app requirements and reflex in the container
RUN pip install -r requirements.txt

# Copy local context to `/app` inside container (see .dockerignore)
COPY . .

# Deploy templates and prepare app
RUN reflex init

# Download all npm dependencies and compile frontend
RUN reflex export --frontend-only --no-zip && mv .web/build/client/* /srv/ && rm -rf .web

# Needed until Reflex properly passes SIGTERM on backend.
STOPSIGNAL SIGKILL

EXPOSE $PORT

# Apply migrations before starting the backend.
CMD [ -d alembic ] && reflex db migrate; \
   caddy start && \
   redis-server --daemonize yes && \
   exec reflex run --env prod --backend-only