FROM rocker/shiny:4.5.2

# 1. System dependencies (spatial stack required for sf)
RUN apt-get update && apt-get install -y --no-install-recommends \
    build-essential \
    cmake \
    curl \
    libabsl-dev \
    libcurl4-openssl-dev \
    libfontconfig1-dev \
    libfreetype6-dev \
    libfribidi-dev \
    libgdal-dev \
    libgeos-dev \
    libharfbuzz-dev \
    libicu-dev \
    libjpeg-dev \
    libpng-dev \
    libproj-dev \
    libssl-dev \
    libtiff5-dev \
    libudunits2-dev \
    libxml2-dev \
    pkg-config \
    proj-bin \
    proj-data \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /srv/shiny-server

# 2. Copy lockfile first for layer caching
COPY renv.lock .

# 3. Install packages into site-library (accessible to all users including shiny)
ENV RENV_PATHS_LIBRARY=/usr/local/lib/R/site-library

RUN R -q -e "install.packages('renv', repos='https://cloud.r-project.org')" \
    && R -q -e "renv::restore(library='/usr/local/lib/R/site-library', prompt=FALSE)"

# 4. Copy application code
COPY . .

# 5. Permissions
RUN chown -R shiny:shiny /srv/shiny-server

EXPOSE 3838
CMD ["/usr/bin/shiny-server"]
