FROM rust:latest as builder

WORKDIR /usr/src/app

# Install dependencies
RUN apt-get update && \
    apt-get install -y libpq-dev protobuf-compiler && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*

# Create a new empty shell project
RUN USER=root cargo new --bin bluesmoke-ai
WORKDIR /usr/src/app/bluesmoke-ai

# Copy over manifests
COPY ./Cargo.toml ./Cargo.toml
COPY ./Cargo.lock ./Cargo.lock

# Build dependencies - this is the caching Docker layer!
RUN cargo build --release
RUN rm src/*.rs

# Copy actual source code
COPY ./src ./src
COPY ./proto ./proto
COPY ./build.rs ./build.rs
COPY ./diesel.toml ./diesel.toml
COPY ./migrations ./migrations

# Build the application
RUN cargo build --release

# Runtime stage
FROM debian:bullseye-slim

WORKDIR /usr/local/bin

# Install runtime dependencies
RUN apt-get update && \
    apt-get install -y libpq5 ca-certificates && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*

# Copy the build artifact from the builder stage
COPY --from=builder /usr/src/app/bluesmoke-ai/target/release/bluesmoke-ai .

# Copy the .env file
# Ensure we're using the correct .env.rust file from the root directory
COPY ./.env.rust ./.env

# Set the startup command
CMD ["./bluesmoke-ai"]