FROM python:3.11-slim

WORKDIR /app

ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1

COPY requirements.txt .

# Install git for private arqera-math dependency, then clean up.
# GitHub auth is mounted as a BuildKit secret so it does not leak into image metadata.
RUN --mount=type=secret,id=github_token \
    apt-get update && apt-get install -y --no-install-recommends git \
    && if [ -f /run/secrets/github_token ]; then git config --global url."https://$(cat /run/secrets/github_token)@github.com/".insteadOf "https://github.com/"; fi \
    && pip install --no-cache-dir --upgrade pip \
    && pip install --no-cache-dir -r requirements.txt \
    && git config --global --remove-section url."https://$(cat /run/secrets/github_token 2>/dev/null)@github.com/" 2>/dev/null || true \
    && apt-get purge -y git && apt-get autoremove -y && rm -rf /var/lib/apt/lists/*

COPY . .

# Create non-root user for security (required by k8s runAsNonRoot)
RUN groupadd -g 1001 appgroup && useradd -r -u 1001 -g appgroup appuser
RUN chown -R appuser:appgroup /app
USER 1001

EXPOSE 8000

CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
