# Builder stage using slim Python image
FROM python:3.11-slim as builder

# Install system dependencies for building
RUN apt-get update && apt-get install -y \
    gcc \
    python3-dev \
    && rm -rf /var/lib/apt/lists/*

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

# Copy requirements first to leverage Docker cache
COPY requirements.txt .

# Install Python dependencies with cache dir
RUN --mount=type=cache,target=/root/.cache/pip \
    pip install --no-cache-dir -r requirements.txt

# Final stage - using Alpine with build dependencies
FROM python:3.11-alpine3.18

# Install runtime and build dependencies
RUN apk add --no-cache \
    tini \
    build-base \
    python3-dev \
    openblas-dev \
    && rm -rf /var/cache/apk/*

# Set working directory
WORKDIR /app

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

# Reinstall numpy to ensure Alpine compatibility
RUN pip install --no-cache-dir --force-reinstall numpy

# Create a non-root user
RUN addgroup -S bot && adduser -S bot -G bot

# Copy necessary files
COPY --chown=bot:bot *.py ./
COPY --chown=bot:bot entrypoint.sh ./

# Create directories for persistent storage
RUN mkdir -p logs embed && \
    chown -R bot:bot /app logs embed && \
    chmod -R 777 /app logs embed

# Switch to non root user
USER bot

# Set environment variables for configuration
ENV PYTHONUNBUFFERED=1
ENV CONFIG_PATH=/app/config.ini
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONPYCACHEPREFIX=/tmp

# Run the bot using tini and entrypoint script
ENTRYPOINT ["tini", "--", "/bin/sh", "entrypoint.sh"]