ARG NODE_VERSION=24
ARG PYTHON_VERSION=3.14

############
# build ui #
############

ARG NODE_VERSION
FROM node:${NODE_VERSION} AS build-ui

# env setup
WORKDIR /usr/local/src/advent22_ui

# install advent22_ui dependencies
RUN --mount=type=bind,source=ui/package.json,target=package.json \
    --mount=type=bind,source=ui/yarn.lock,target=yarn.lock \
    set -ex; \
    \
    corepack enable; \
    yarn install --frozen-lockfile;

# copy and build advent22_ui
COPY ui ./
RUN set -ex; \
    \
    yarn dlx update-browserslist-db@latest; \
    yarn build --dest /tmp/advent22_ui; \
    # exclude webpack-bundle-analyzer output
    rm -f /tmp/advent22_ui/report.html;


###############
# install api #
###############

ARG PYTHON_VERSION
FROM dhi.io/python:${PYTHON_VERSION}-dev AS install-api

# env setup for uv
ENV UV_COMPILE_BYTECODE=1 \
    UV_NO_DEV=1 \
    UV_LINK_MODE="copy"

EXPOSE 8000

# install advent22_api deps
WORKDIR /opt/advent22/api

RUN --mount=from=ghcr.io/astral-sh/uv,source=/uv,target=/bin/uv \
    --mount=type=cache,target=/root/.cache/uv \
    --mount=type=bind,source=api/uv.lock,target=uv.lock \
    --mount=type=bind,source=api/pyproject.toml,target=pyproject.toml \
    \
    uv sync \
        --locked \
        --no-install-project \
        --no-editable \
    ;

# install advent22_api
COPY api ./
RUN --mount=from=ghcr.io/astral-sh/uv,source=/uv,target=/bin/uv \
    --mount=type=cache,target=/root/.cache/uv \
    \
    uv sync \
        --locked \
        --no-editable \
    ;

# add prepared advent22_ui
COPY --from=build-ui /tmp/advent22_ui /opt/advent22/ui/

# prepare data directory
WORKDIR /opt/advent22/data
RUN chown -R nobody:nobody ./


####################
# production image #
####################

ARG PYTHON_VERSION
FROM dhi.io/python:${PYTHON_VERSION} AS production

ENV PATH="/opt/advent22/api/.venv/bin:$PATH"
CMD [ "advent22" ]

COPY --from=install-api /opt /opt/

WORKDIR /opt/advent22/data
VOLUME [ "/opt/advent22/data" ]

# run as unprivileged user
USER nobody
