# ── SigMA2 Dockerfile ────────────────────────────────────────────────
# Multi-stage build: compile Rust extension in builder, copy into slim runtime.
# Usage:
#   docker build -t sigma2 .
#   docker run -it sigma2 python -c "import sigma2"
# ──────────────────────────────────────────────────────────────────────

# ==========================  BUILDER  ==========================
FROM python:3.10-bookworm AS builder

# Rust toolchain (needed by maturin / PyO3)
ENV RUSTUP_HOME=/usr/local/rustup \
    CARGO_HOME=/usr/local/cargo \
    PATH="/usr/local/cargo/bin:${PATH}"
RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs \
    | sh -s -- -y --default-toolchain stable --profile minimal

# System libraries required at compile time
RUN apt-get update && apt-get install -y --no-install-recommends \
    build-essential \
    cmake \
    pkg-config \
    libssl-dev \
    && rm -rf /var/lib/apt/lists/*

# Install maturin
RUN pip install --no-cache-dir maturin>=1.0,\<2.0

# Copy source tree
WORKDIR /build
COPY . .

# Build the wheel (Rust extension + Python package)
RUN maturin build --release --interpreter python3.10 -o /build/dist

# ==========================  RUNTIME  ==========================
FROM python:3.10-slim-bookworm

LABEL maintainer="Jan P Hummel <jan_hummel@hms.harvard.edu>" \
      description="SigMA2 – Mutational Signature Analysis for panel/exome/WGS data" \
      version="0.3.0"

# ── System dependencies ──────────────────────────────────────────
# bedtools    – required by pybedtools (panel simulation)
# r-base      – required for GBM prediction and BSgenome utilities
# libcurl/xml – required by R Bioconductor packages
RUN apt-get update && apt-get install -y --no-install-recommends \
    bedtools \
    r-base \
    r-base-dev \
    libcurl4-openssl-dev \
    libxml2-dev \
    libssl-dev \
    libfontconfig1-dev \
    libharfbuzz-dev \
    libfribidi-dev \
    && rm -rf /var/lib/apt/lists/*

# ── R packages ───────────────────────────────────────────────────
# CRAN: gbm (gradient boosted models used in SigMA prediction)
RUN Rscript -e "install.packages('gbm', repos='https://cloud.r-project.org')"

# Bioconductor: BSgenome, Biostrings, rtracklayer (used by bsgenome_to_fasta.R)
RUN Rscript -e "\
    if (!requireNamespace('BiocManager', quietly=TRUE)) \
        install.packages('BiocManager', repos='https://cloud.r-project.org'); \
    BiocManager::install(c('BSgenome', 'Biostrings', 'rtracklayer'), ask=FALSE, update=FALSE)"

# ── Python package ───────────────────────────────────────────────
COPY --from=builder /build/dist/*.whl /tmp/wheels/
RUN pip install --no-cache-dir /tmp/wheels/*.whl && rm -rf /tmp/wheels

# Optional but commonly used analysis dependencies
RUN pip install --no-cache-dir \
    scikit-learn>=1.3 \
    matplotlib>=3.7 \
    seaborn>=0.13 \
    shap>=0.45 \
    pybedtools>=0.10 \
    tabulate>=0.9 \
    anndata>=0.10

WORKDIR /data
ENTRYPOINT ["python"]