FROM nvidia/cuda:12.9.2-devel-ubuntu22.04

ENV DEBIAN_FRONTEND=noninteractive
ENV TZ=Europe/Paris

# Install system packages + Miniforge for PDAL >= 2.5 (Ubuntu 22.04 ships PDAL 2.3 which can't read COPC v1.1)
RUN apt-get update && apt-get install -y --no-install-recommends \
    gdal-bin \
    python3-gdal \
    python3-pip \
    python3-dev \
    build-essential \
    wget \
    && rm -rf /var/lib/apt/lists/* \
    && wget -q https://github.com/conda-forge/miniforge/releases/latest/download/Miniforge3-Linux-x86_64.sh -O /tmp/miniforge.sh \
    && bash /tmp/miniforge.sh -b -p /opt/conda \
    && rm /tmp/miniforge.sh \
    && /opt/conda/bin/conda install -y -c conda-forge pdal \
    && ln -sf /opt/conda/bin/pdal /usr/local/bin/pdal \
    && /opt/conda/bin/conda clean -afy

WORKDIR /app

# Install Python packages via pip (single list: requirements.txt)
COPY requirements.txt .
RUN pip3 install --no-cache-dir -r requirements.txt

# CuPy on CUDA 12.9 with JIT compilation (CUPY_CUDA_COMPILE_WITH_CACHE=1).
# JIT allows CuPy to compile kernels at runtime for GPU architectures not in
# the pre-built wheel (sm_89 = RTX 4060 Ti, sm_120 = RTX 5060 Ti).
# nvcc must be in PATH at runtime for JIT compilation.
ENV CUPY_CUDA_COMPILE_WITH_CACHE=1
# numba kernel cache (relief_oriente, flow accumulation): without it, every
# worker (spawned process per tile) recompiles its kernels (~1 s per tile).
ENV NUMBA_CACHE_DIR=/tmp/numba-cache
ENV PATH=/usr/local/cuda/bin:${PATH}
RUN pip3 install --no-cache-dir cupy-cuda12x

# Copy and install the pipeline package
COPY setup.py .
COPY lidar_pipeline/ ./lidar_pipeline/
RUN pip3 install --no-cache-dir .

# Map interface CSS/JS (app.js/app.css from web/map.*, + vendored Leaflet)
# baked into the image: mapserve serves them from mapserve_assets/ of the
# installed package. cd /tmp: without it, python3 -c puts the current
# directory (/app, the source copy) on sys.path and the bake would land in
# that copy instead of the installed package (dist-packages) the container
# uses at runtime.
RUN cd /tmp && python3 -c "import pathlib, lidar_pipeline.mapui as m; m.write_map_assets(pathlib.Path(m.__file__).resolve().parent / m.ASSETS_DIRNAME)"


# Create user with uid/gid 1000:1000 and run as that user
RUN groupadd -g 1000 lidar && \
    useradd -u 1000 -g lidar -m lidar && \
    mkdir -p /data/output /data/input && \
    chown -R lidar:lidar /data /data/output /data/input

WORKDIR /data

USER lidar

VOLUME ["/data"]

CMD ["python3", "-m", "lidar_pipeline", "/data/input", "-o", "/data/output"]