# syntax=docker/dockerfile:1.4

# ============================================================================
# Stage 1: Chef - Prepare cargo-chef for dependency caching
# ============================================================================
FROM rust:1.95-slim AS chef

RUN apt-get update && apt-get install -y --no-install-recommends \
    pkg-config \
    libssl-dev \
    curl \
    && rm -rf /var/lib/apt/lists/*

RUN rustup component add rustfmt

RUN cargo install cargo-chef --locked

WORKDIR /app

# ============================================================================
# Stage 2: Planner - Analyze dependencies
# ============================================================================
FROM chef AS planner

COPY Cargo.toml Cargo.lock rust-toolchain.toml ./
COPY crates crates
COPY integrations integrations
COPY docs docs

RUN cargo chef prepare --recipe-path recipe.json

# ============================================================================
# Stage 3: Builder - Build dependencies (cached) then application
# ============================================================================
FROM chef AS builder

# Copy recipe and build dependencies first (cached layer)
COPY --from=planner /app/recipe.json recipe.json
RUN cargo chef cook --release --recipe-path recipe.json

# Copy source and build application
COPY Cargo.toml Cargo.lock rust-toolchain.toml ./
COPY crates crates
COPY integrations integrations
COPY docs docs

RUN cargo build --release -p everruns-server

# ============================================================================
# Stage 4: Runtime - Distroless production image (minimal size and security)
# ============================================================================
FROM gcr.io/distroless/cc-debian12:nonroot@sha256:bd2899c12b335c827750ccf2359879eab09c09b206023dcebea408947d54127c AS runtime

WORKDIR /app

COPY --from=builder /app/target/release/everruns-server /app/everruns-server

EXPOSE 9000
EXPOSE 9001

ENV RUST_LOG=info
ENV HTTP_ADDR=0.0.0.0:9000

CMD ["/app/everruns-server"]
