# syntax=docker/dockerfile:1.7

ARG RUST_IMAGE=rust:1.99.0-bookworm
ARG RUNTIME_IMAGE=debian:bookworm-slim

FROM ${RUST_IMAGE} AS chef
RUN cargo install cargo-chef --locked
WORKDIR /app

FROM chef AS planner
COPY Cargo.toml Cargo.lock build.rs ./
COPY crates/ ./crates/
COPY src/ ./src/
COPY ares.example.toml ./ares.example.toml
RUN cargo chef prepare --recipe-path recipe.json

FROM chef AS builder

# The features the image's binary is built with.
#
# `http` and `cli` are not optional: the `ares-server` binary target
# declares `required-features = ["http", "cli"]`, and cargo refuses to
# build a target whose required features are not enabled. `postgres` is
# the database the server talks to.
#
# There is no `openai` feature. It was removed with the NVIDIA rework
# and asking for it fails with "the package 'ares-server' does not
# contain this feature: openai".
ARG FEATURES="postgres,mcp,http,cli"
ARG EXTRA_CARGO_ARGS="--no-default-features"

COPY --from=planner /app/recipe.json recipe.json
RUN --mount=type=cache,target=/usr/local/cargo/registry \
    --mount=type=cache,target=/usr/local/cargo/git \
    --mount=type=cache,target=/app/target \
    cargo chef cook --release ${EXTRA_CARGO_ARGS} --features "${FEATURES}" --recipe-path recipe.json

COPY Cargo.toml Cargo.lock build.rs ./
COPY crates/ ./crates/
COPY src/ ./src/
COPY ares.example.toml ./ares.example.toml

RUN --mount=type=cache,target=/usr/local/cargo/registry \
    --mount=type=cache,target=/usr/local/cargo/git \
    --mount=type=cache,target=/app/target \
    cargo build --release ${EXTRA_CARGO_ARGS} --features "${FEATURES}" --bin ares-server && \
    cp /app/target/release/ares-server /tmp/ares-server

FROM ${RUNTIME_IMAGE} AS runtime

RUN apt-get update && \
    apt-get install -y --no-install-recommends ca-certificates curl && \
    rm -rf /var/lib/apt/lists/* && \
    useradd --create-home --uid 1000 --shell /usr/sbin/nologin ares

WORKDIR /app

COPY --from=builder /tmp/ares-server /usr/local/bin/ares-server
COPY ares.example.toml /app/ares.example.toml

RUN mkdir -p /app/data /app/config && chown -R ares:ares /app

USER ares

ENV RUST_LOG=info
ENV ARES_CONFIG=/app/ares.toml

EXPOSE 3000

HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
    CMD curl -fsS http://127.0.0.1:3000/health || exit 1

CMD ["ares-server"]
