# UV example repository: https://github.com/astral-sh/uv-docker-example
# UV documentation: https://docs.astral.sh/uv/guides/integration/docker/#available-images

FROM ghcr.io/astral-sh/uv:trixie-slim AS builder

# Compile python code to bytecode for faster startup, set link mode to copy to avoid warning about caching in different file system
ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy
# Exclude the development dependencies, equivalent to --no-dev passed in CLI
ENV UV_NO_DEV=1

# Configure the Python directory so it is consistent
ENV UV_PYTHON_INSTALL_DIR=/python
# Only use the managed Python version
ENV UV_PYTHON_PREFERENCE=only-managed

# Install Python before the project for caching
RUN uv python install

# Install gammalearn in /gammalearn
WORKDIR /gammalearn

# Install git required for setuptools_scm
RUN apt update && apt install -y git g++ gcc

# install dependencies without gammalearn first to cache layer
RUN --mount=type=cache,target=/root/.cache/uv \
    --mount=type=bind,source=uv.lock,target=uv.lock \
    --mount=type=bind,source=pyproject.toml,target=pyproject.toml \
    uv sync --locked --extra gpu --no-install-project --no-editable
COPY . /gammalearn
# install with gpu support
RUN --mount=type=cache,target=/root/.cache/uv \
    uv sync --locked --extra gpu --no-editable

# Multistage build: final image doesn't even have uv
# Note: debian version must match between the 2 stages, otherwise glibc differences can cause astropy to fail "ImportError GLIBC_2.38 not found"
FROM debian:trixie-slim

# Setup a non-root user
RUN groupadd --system --gid 999 GAMMALEARN_USER \
 && useradd --system --gid 999 --uid 999 --create-home GAMMALEARN_USER

# Copy the Python version
COPY --from=builder /python /python
# Copy the application from the builder
COPY --from=builder --chown=GAMMALEARN_USER:GAMMALEARN_USER /gammalearn /gammalearn

# Place executables in the environment at the front of the path
ENV PATH="/gammalearn/.venv/bin:$PATH"

# Make default user GAMMALEARN_USER: a non-root user
USER GAMMALEARN_USER

# Use `/gammalearn` as the working directory
WORKDIR /gammalearn
