# Multi-stage build for ant-quic with optimized caching
FROM rust:1.85-slim AS builder

# Install build dependencies (cached layer)
RUN apt-get update && apt-get install -y \
    pkg-config \
    libssl-dev \
    protobuf-compiler \
    && rm -rf /var/lib/apt/lists/*

# Set build arguments for resource-constrained environments
ARG CARGO_BUILD_JOBS=2
ARG CARGO_INCREMENTAL=0
ARG CARGO_NET_RETRY=10

ENV CARGO_BUILD_JOBS=${CARGO_BUILD_JOBS} \
    CARGO_INCREMENTAL=${CARGO_INCREMENTAL} \
    CARGO_NET_RETRY=${CARGO_NET_RETRY}

# Create app directory
WORKDIR /usr/src/ant-quic

# Copy only dependency files first for better caching
COPY Cargo.toml Cargo.lock ./

# Create dummy source structure and benches to satisfy Cargo.toml
RUN mkdir -p src/bin benches && \
    echo "fn main() {}" > src/bin/ant-quic.rs && \
    echo "pub fn lib() {}" > src/lib.rs && \
    echo "fn main() {}" > benches/quic_benchmarks.rs && \
    echo "fn main() {}" > benches/relay_queue.rs && \
    echo "fn main() {}" > benches/candidate_discovery.rs && \
    echo "fn main() {}" > benches/nat_traversal.rs && \
    echo "fn main() {}" > benches/address_discovery_bench.rs && \
    echo "fn main() {}" > benches/connection_management.rs && \
    echo "fn main() {}" > benches/nat_traversal_performance.rs

# Build dependencies only (this layer gets cached)
RUN cargo build --release --bin ant-quic && \
    rm -rf src target/release/ant-quic* target/release/deps/ant_quic*

# Copy actual bench files
COPY benches ./benches/

# Copy the actual source code
COPY src ./src/
COPY examples ./examples/

# Touch the main files to ensure rebuild
RUN touch src/main.rs src/lib.rs src/bin/ant-quic.rs 2>/dev/null || true

# Build the actual project with limited parallelism
RUN cargo build --release --bin ant-quic --examples

# Runtime stage - smaller final image
FROM debian:bookworm-slim AS runtime

# Install runtime dependencies and debugging tools
RUN apt-get update && apt-get install -y \
    libssl3 \
    ca-certificates \
    iproute2 \
    iptables \
    iputils-ping \
    tcpdump \
    net-tools \
    dnsutils \
    netcat-traditional \
    iperf3 \
    curl \
    && rm -rf /var/lib/apt/lists/*

# Create non-root user for running the application
RUN useradd -m -u 1000 antquic

# Copy binary from builder
COPY --from=builder /usr/src/ant-quic/target/release/ant-quic /usr/local/bin/
COPY --from=builder /usr/src/ant-quic/target/release/examples/* /usr/local/bin/

# Set up directories
RUN mkdir -p /app/logs /app/data && \
    chown -R antquic:antquic /app

WORKDIR /app

# Switch to non-root user
USER antquic

# Default command
CMD ["ant-quic", "--help"]

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
    CMD netcat -z localhost 9000 || exit 1