# Multi-stage build for Foxhunt HFT Trading System
# This is the main Dockerfile for building any service in the workspace
# Usage: docker build --build-arg SERVICE_NAME=trading_service -t foxhunt-trading .

FROM nvidia/cuda:12.1-devel-ubuntu22.04 as builder

# Accept build argument for service selection
ARG SERVICE_NAME=trading_service
ARG BUILD_MODE=release

# Install Rust and system dependencies
RUN apt-get update && apt-get install -y \
    curl \
    build-essential \
    pkg-config \
    libssl-dev \
    libpq-dev \
    protobuf-compiler \
    ca-certificates \
    && rm -rf /var/lib/apt/lists/*

# Install Rust with stable toolchain
RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
ENV PATH="/root/.cargo/bin:${PATH}"

# Set workspace directory
WORKDIR /workspace

# Copy workspace Cargo files first for better layer caching
COPY Cargo.toml Cargo.lock ./

# Copy all crates and services for workspace build
COPY crates/ ./crates/
COPY services/ ./services/
COPY tli/ ./tli/

# Copy additional directories that may be referenced
COPY config/ ./config/
COPY database/ ./database/

# Build the specific service based on build argument
RUN if [ "$BUILD_MODE" = "debug" ]; then \
        cargo build -p $SERVICE_NAME; \
    else \
        cargo build --release -p $SERVICE_NAME; \
    fi

# === RUNTIME IMAGE ===
FROM nvidia/cuda:12.1-runtime-ubuntu22.04

# Accept build arguments for runtime configuration
ARG SERVICE_NAME=trading_service
ARG BUILD_MODE=release

# Install runtime dependencies
RUN apt-get update && apt-get install -y \
    ca-certificates \
    libssl3 \
    libpq5 \
    curl \
    # Terminal dependencies for TLI
    libncurses6 \
    libncursesw6 \
    terminfo \
    && rm -rf /var/lib/apt/lists/*

# Create app user for security
RUN groupadd -r foxhunt && useradd -r -g foxhunt foxhunt

# Create directories with proper permissions
RUN mkdir -p /app/config /app/data /app/logs /app/cache \
    && chown -R foxhunt:foxhunt /app

# Copy binary from builder stage
COPY --from=builder \
    /workspace/target/${BUILD_MODE}/${SERVICE_NAME} \
    /app/${SERVICE_NAME}
RUN chmod +x /app/${SERVICE_NAME}

# Copy configuration files
COPY config/ /app/config/
COPY database/ /app/database/

# Set proper ownership
RUN chown -R foxhunt:foxhunt /app

USER foxhunt
WORKDIR /app

# Set environment variables
ENV RUST_LOG=info
ENV FOXHUNT_CONFIG=/app/config/config.toml
ENV SERVICE_NAME=${SERVICE_NAME}

# Health check (will be overridden in docker-compose for specific ports)
HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \
    CMD curl -f http://localhost:8080/health || exit 1

# Default command - run the service
CMD ./${SERVICE_NAME}