# syntax=docker/dockerfile:1.6

# Multi-stage build for R package: omopduckdb
# (also installs and tests the Python package, omop-duck-db, since this repo
# ships both -- usethis::use_dockerfile() only knows about the R side)
#
# NOTE on the repos date: usethis::use_dockerfile() date-pins the Posit
# Package Manager snapshot to Sys.Date() at generation time. On this machine
# that produced a *future* date (2026-07-31) that Posit's snapshot service
# won't have data for yet in the real world -- swapped for the rolling
# `/latest` alias instead. Worth fixing upstream in the PR: pinning to
# Sys.Date() is only safe if that's guaranteed to be <= the real current date.

# Exact Python for the image (must match the study's reference workstation; CI fails if the built image reports another version).
ARG PYTHON_VERSION=3.13.17

# Stage 1: builder
FROM rocker/r-ver:4.4.2 AS builder
ARG PYTHON_VERSION

# The repo's .Rprofile activates renv on load; renv's own project library is
# irrelevant here (this image installs straight into /rlib instead), and
# without this it silently swaps .libPaths() to an empty renv library,
# hiding everything just installed. Same fix needed locally on Windows.
ENV RENV_CONFIG_AUTOLOADER_ENABLED=FALSE
ENV R_LIBS=/rlib
WORKDIR /build

# Install system dependencies (git from the generator; python3 added so this
# stage can also build the Python package)
RUN apt-get update && apt-get install -y --no-install-recommends \
        git python3 python3-pip python3-venv libicu-dev \
    && rm -rf /var/lib/apt/lists/*

# Install R packages into a dedicated library
RUN mkdir -p /rlib && Rscript -e 'install.packages(c("bigrquery", "CommonDataModel", "DBI", "digest", "duckdb", "googledrive", "quarto", "stringr", "testthat", "usethis", "yaml", "Matrix", "arrow", "jsonlite", "dplyr", "withr", "rmarkdown", "knitr"), repos = "https://packagemanager.posit.co/cran/__linux__/noble/latest", lib = "/rlib")'

# Build + test both packages in the builder stage, so a failing test fails
# the image build, not just a later `docker run`.
COPY . /build
RUN R_LIBS=/rlib R CMD INSTALL --no-multiarch --with-keep.source --install-tests /build --library=/rlib
RUN cd /build/tests && R_LIBS=/rlib Rscript testthat.R

# Python is pinned to an exact version, the same as the study's reference workstation, instead of taking whatever `python3` the
# base image's Ubuntu ships (noble: 3.12). uv installs a standalone CPython build into /opt/python, which the runtime stage copies
# at the same path. CI checks that the built image reports exactly this version.
COPY --from=ghcr.io/astral-sh/uv:0.13.8 /uv /usr/local/bin/uv
RUN UV_PYTHON_INSTALL_DIR=/opt/python uv python install "${PYTHON_VERSION}" \
    && "$(UV_PYTHON_INSTALL_DIR=/opt/python uv python find --managed-python "${PYTHON_VERSION}")" -m venv /pyvenv \
    && test "$(/pyvenv/bin/python -c 'import platform; print(platform.python_version())')" = "${PYTHON_VERSION}"
RUN /pyvenv/bin/python -m pip --version \
    && /pyvenv/bin/pip install --no-cache-dir --index-url https://download.pytorch.org/whl/cpu "torch>=2.0" \
    && /pyvenv/bin/pip install --no-cache-dir "/build[dev,bundle,deep,postgres-embedded]" \
    && R_LIBS=/rlib PATH="/pyvenv/bin:$PATH" /pyvenv/bin/python -m pytest /build/tests -v

# Stage 2: final runtime
FROM rocker/r-ver:4.4.2
ARG PYTHON_VERSION

LABEL org.opencontainers.image.title="omopduckdb"

# Create non-root user (skip if already exists)
RUN id -u ruser >/dev/null 2>&1 || useradd -m -u 1000 ruser

# Install runtime system deps
RUN apt-get update && apt-get install -y --no-install-recommends \
        git libicu-dev ca-certificates curl \
    && rm -rf /var/lib/apt/lists/*

# Quarto CLI renders the study manuscript (run_study -> <prefix>_Manuscript.docx / .pdf). It bundles Pandoc and Typst, so the PDF
# needs no LaTeX. TARGETARCH (amd64 / arm64) is set by buildx, so the same Dockerfile builds the image for a DGX Spark (arm64).
# Pandoc and Typst are linked onto the PATH too, for rmarkdown::render() and the Pandoc fallback.
ARG QUARTO_VERSION=1.10.19
ARG TARGETARCH
RUN arch="${TARGETARCH:-$(dpkg --print-architecture)}" \
    && curl -fsSL "https://github.com/quarto-dev/quarto-cli/releases/download/v${QUARTO_VERSION}/quarto-${QUARTO_VERSION}-linux-${arch}.tar.gz" \
       | tar -xz -C /opt \
    && ln -s "/opt/quarto-${QUARTO_VERSION}/bin/quarto" /usr/local/bin/quarto \
    && ln -s "$(find /opt/quarto-${QUARTO_VERSION}/bin/tools -name pandoc -type f | head -n 1)" /usr/local/bin/pandoc \
    && ln -s "$(find /opt/quarto-${QUARTO_VERSION}/bin/tools -name typst -type f | head -n 1)" /usr/local/bin/typst \
    && quarto --version && pandoc --version | head -n 1 && typst --version

WORKDIR /workspace

# Copy R packages and the built Python venv from builder
COPY --from=builder /rlib /rlib
COPY --from=builder /opt/python /opt/python
COPY --from=builder /pyvenv /pyvenv
ENV RENV_CONFIG_AUTOLOADER_ENABLED=FALSE
ENV R_LIBS=/rlib
ENV PATH="/pyvenv/bin:$PATH"
RUN test "$(python -c 'import platform; print(platform.python_version())')" = "${PYTHON_VERSION}" && python3 --version
# The manuscript cites omop-duck-db with the installed package's version through grateful_py: both must resolve in the image.
RUN python -c "import grateful_py, omop_etl; from omop_etl.package_citations import omop_duck_db_version as v; assert v() == omop_etl.__version__, (v(), omop_etl.__version__); print('grateful_py', grateful_py.__version__, '| omop-duck-db', v())"

# Copy project source
COPY --chown=ruser:ruser . .

# Ensure working directory is owned by non-root user
RUN chown -R ruser:ruser /workspace

# Switch to non-root user
USER ruser

# Check the image: python scripts/container_smoke_test.py (manuscript DOCX/PDF, privacy scan, Delta Lake, embedded PostgreSQL, R + rmarkdown)
# The embedded PostgreSQL (postgres-embedded extra) refuses to run as root, which is one more reason the image runs as ruser.
# Default: R interactive
CMD ["R", "--no-save"]
