# Pin the builder to bookworm so its glibc matches the bookworm-slim runtime;
# the default tag tracks trixie, whose `libmvec.so.1` is absent on bookworm.
FROM rust:1.91-bookworm AS builder
WORKDIR /app

# 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. The full rust image already ships g++/pkg-config/libssl.
RUN apt-get update && apt-get install -y --no-install-recommends 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
WORKDIR /srv
RUN useradd --system --home /srv tidal && \
    apt-get update && apt-get install -y ca-certificates curl && \
    rm -rf /var/lib/apt/lists/*

COPY --from=builder /app/target/release/tidal-server /usr/local/bin/tidal-server
COPY tidal-server/config /etc/tidal-server

USER tidal
EXPOSE 9400 9091

HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
    CMD curl -f -H "Authorization: Bearer ${TIDAL_API_KEY:-}" http://localhost:9400/health || exit 1

ENTRYPOINT ["tidal-server", "standalone", \
    "--listen", "0.0.0.0:9400", \
    "--metrics", "0.0.0.0:9091"]
