# ==============================================
# LLMHosts -- Production Multi-Stage Dockerfile
# Separate from Dockerfile.dev (development)
# ==============================================

# ---- Stage 1: Builder ----
FROM python:3.12-slim AS builder
WORKDIR /build

# Install Rust toolchain
RUN apt-get update && apt-get install -y --no-install-recommends curl gcc g++ libc6-dev pkg-config && \
    curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y && \
    apt-get purge -y curl && apt-get autoremove -y && rm -rf /var/lib/apt/lists/*
ENV PATH="/root/.cargo/bin:${PATH}"

# Install maturin build tool
RUN pip install --no-cache-dir "maturin>=1.8"

# Copy Python source and project metadata
COPY pyproject.toml README.md ./
COPY llmhosts/ ./llmhosts/

# Copy Rust workspace and crate sources
COPY Cargo.toml Cargo.lock ./
COPY src/ ./src/
COPY llmhosts_core/ ./llmhosts_core/
COPY llmhosts_gpu/ ./llmhosts_gpu/
COPY relay_core/ ./relay_core/
COPY router_core/ ./router_core/

# Build wheel with maturin
RUN maturin build --release --out /build/dist

# ---- Stage 2: Runtime ----
FROM python:3.12-slim AS runtime

# Security: non-root user
RUN groupadd --gid 1000 llmhost && \
    useradd --uid 1000 --gid llmhost --shell /bin/bash --create-home llmhost

WORKDIR /app

# Install wheel from builder
COPY --from=builder /build/dist/*.whl /tmp/
RUN pip install --no-cache-dir /tmp/*.whl && \
    rm -rf /tmp/*.whl /root/.cache

# Data directory
RUN mkdir -p /home/llmhost/.llmhosts && \
    chown -R llmhost:llmhost /home/llmhost/.llmhosts

USER llmhost
EXPOSE 4000

HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
    CMD python -c "import httpx; httpx.get('http://localhost:4000/health')" || exit 1

ENTRYPOINT ["llmhosts"]
CMD ["serve"]
