# Multi-stage build for DexOrder user container
FROM python:3.11-slim AS builder

WORKDIR /build

# Install build dependencies including protobuf compiler
RUN apt-get update && apt-get install -y --no-install-recommends \
    gcc \
    g++ \
    protobuf-compiler \
    && rm -rf /var/lib/apt/lists/*

# Copy dependency specifications
COPY setup.py .
COPY dexorder/ dexorder/

# Copy protobuf definitions (copied by bin/build from canonical /protobuf/)
COPY protobuf/ protobuf/

# Compile protobufs to Python
RUN mkdir -p dexorder/generated && \
    protoc --python_out=dexorder/generated --proto_path=protobuf protobuf/*.proto && \
    touch dexorder/generated/__init__.py

# Install dependencies to a target directory
RUN pip install --no-cache-dir --target=/build/deps .

# =============================================================================
# Runtime stage
# =============================================================================
FROM python:3.11-slim

WORKDIR /app

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

# Create non-root user
RUN groupadd -r dexorder && useradd -r -g dexorder -u 1000 dexorder

# Copy installed Python packages from builder
COPY --from=builder /build/deps /usr/local/lib/python3.11/site-packages/

# Copy application code
COPY dexorder/ /app/dexorder/
COPY main.py /app/

# Copy generated protobuf code from builder
COPY --from=builder /build/dexorder/generated/ /app/dexorder/generated/

# Create directories for config, secrets, and data
RUN mkdir -p /app/config /app/secrets /app/data && \
    chown -R dexorder:dexorder /app

# Create writable tmp directory (read-only rootfs requirement)
RUN mkdir -p /tmp && chmod 1777 /tmp

# Switch to non-root user
USER dexorder

# Environment variables (can be overridden in k8s)
ENV PYTHONUNBUFFERED=1 \
    LOG_LEVEL=INFO \
    CONFIG_PATH=/app/config/config.yaml \
    SECRETS_PATH=/app/config/secrets.yaml \
    ZMQ_XPUB_PORT=5570 \
    ZMQ_GATEWAY_ENDPOINT=tcp://gateway:5571 \
    MCP_SERVER_NAME=dexorder-user \
    MCP_TRANSPORT=sse \
    MCP_HTTP_PORT=3000 \
    MCP_HTTP_HOST=0.0.0.0 \
    IDLE_TIMEOUT_MINUTES=15 \
    ENABLE_IDLE_SHUTDOWN=true

# Health check endpoint (simple check if process is running)
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
    CMD python -c "import sys; sys.exit(0)"

# Run the main application
ENTRYPOINT ["python", "/app/main.py"]
