# AI Cryptographic Threat Detection Service
# High-Performance Multi-stage build for production

# Stage 1: Build with all dependencies
FROM python:3.11-slim AS builder

WORKDIR /build

# Install build dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
    build-essential \
    && rm -rf /var/lib/apt/lists/*

# Create virtual environment for cleaner dependency management
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"

# Install Python dependencies first (cacheable layer)
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Copy proto files and generate Python stubs
COPY proto/ ./proto/
RUN mkdir -p ./generated && \
    python -m grpc_tools.protoc \
    -I./proto \
    --python_out=./generated \
    --grpc_python_out=./generated \
    ./proto/detection.proto

# Stage 2: Production runtime
FROM python:3.11-slim AS production

# Security: Create non-root user early
RUN useradd --create-home --shell /bin/bash --uid 1000 aidetect

WORKDIR /app

# Copy virtual environment from builder
COPY --from=builder --chown=aidetect:aidetect /opt/venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"

# Copy generated protobuf files
COPY --from=builder --chown=aidetect:aidetect /build/generated/*.py ./src/

# Copy application code
COPY --chown=aidetect:aidetect src/ ./src/

# Switch to non-root user
USER aidetect

# Environment configuration
ENV PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1 \
    PYTHONPATH=/app/src \
    # Server ports
    GRPC_PORT=50051 \
    PORT=8080 \
    HOST=0.0.0.0 \
    # Performance tuning
    GRPC_MAX_WORKERS=10 \
    GRPC_MAX_CONCURRENT=1000 \
    # gRPC optimization
    GRPC_VERBOSITY=ERROR \
    GRPC_ENABLE_FORK_SUPPORT=1 \
    # Memory optimization for numpy
    OMP_NUM_THREADS=1 \
    OPENBLAS_NUM_THREADS=1 \
    MKL_NUM_THREADS=1

# Expose ports
EXPOSE 8080 50051

# Health check - uses Python instead of curl for smaller image
HEALTHCHECK --interval=10s --timeout=5s --start-period=30s --retries=3 \
    CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8080/health')" || exit 1

# Run the application
CMD ["python", "-m", "src.main"]
