# Pin the builder to bookworm so its glibc matches the bookworm-slim runtime.
# The default slim tag tracks Debian trixie, whose vectorized-math `libmvec.so.1`
# is absent on bookworm and aborts the binary at startup.
FROM rust:1.91-slim-bookworm AS builder
WORKDIR /build
# protobuf-compiler (protoc) is required by tidal-net's build script (tonic-build
# compiles the WAL-shipping .proto); tidal-server depends on tidal-net for gRPC
# cluster replication. g++ builds the usearch C++ HNSW core.
RUN apt-get update && apt-get install -y pkg-config libssl-dev g++ protobuf-compiler && rm -rf /var/lib/apt/lists/*

# Copy workspace manifests first for layer caching.
COPY Cargo.toml Cargo.lock ./
COPY tidal/Cargo.toml tidal/Cargo.toml
COPY tidalctl/Cargo.toml tidalctl/Cargo.toml
COPY tidal-server/Cargo.toml tidal-server/Cargo.toml
COPY applications/forage/engine/Cargo.toml applications/forage/engine/Cargo.toml
COPY applications/forage/server/Cargo.toml applications/forage/server/Cargo.toml
COPY applications/forage/embedder/Cargo.toml applications/forage/embedder/Cargo.toml
COPY applications/iknowyou/engine/Cargo.toml applications/iknowyou/engine/Cargo.toml

# Copy full workspace and build.
COPY . .
RUN cargo build -p tidal-server --release

FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates curl && rm -rf /var/lib/apt/lists/*
RUN useradd -m -u 10001 tidal
COPY --from=builder --chown=tidal:tidal /build/target/release/tidal-server /usr/local/bin/tidal-server
RUN mkdir -p /config && chown tidal:tidal /config
USER tidal:tidal
WORKDIR /data
EXPOSE 9500
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
  CMD curl -sf http://localhost:${PORT:-9500}/health || exit 1
ENV TIDAL_SERVER_LOG=info
ENV PORT=9500
ENTRYPOINT ["/usr/local/bin/tidal-server"]
CMD ["standalone", "--schema", "/config/schema.yaml", "--data-dir", "/data"]
