# ===========================================================================
# Stage 1: Build & Dependency Wheel Cache
# ===========================================================================
FROM python:3.12-slim AS builder

WORKDIR /build

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

COPY pyproject.toml README.md ./
COPY llm_gateway ./llm_gateway

RUN pip install --no-cache-dir --upgrade pip build wheel && \
    pip wheel --no-cache-dir --wheel-dir=/build/wheels ".[proxy,semantic-cache]"

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

LABEL maintainer="LLM Gateway Team" \
      description="High-Throughput LLM Gateway & Circuit Breaker Proxy"

WORKDIR /app

# Create non-root user and group
RUN groupadd -g 10001 gateway && \
    useradd -u 10001 -g gateway -s /bin/bash -m gateway

# Install runtime dependencies
COPY --from=builder /build/wheels /tmp/wheels
COPY pyproject.toml README.md ./
COPY llm_gateway ./llm_gateway

RUN pip install --no-cache-dir --no-index --find-links=/tmp/wheels /tmp/wheels/*.whl && \
    pip install --no-cache-dir -e ".[proxy,semantic-cache]" && \
    rm -rf /tmp/wheels /root/.cache

# Copy reference configuration
COPY gateway.yaml.example ./gateway.yaml

# Set ownership
RUN chown -R gateway:gateway /app

USER gateway

ENV PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1 \
    GATEWAY_PORT=8000 \
    GATEWAY_HOST=0.0.0.0

EXPOSE 8000

HEALTHCHECK --interval=15s --timeout=5s --start-period=5s --retries=3 \
    CMD python3 -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/health/live')" || exit 1

CMD ["uvicorn", "llm_gateway.proxy.app:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--workers", "4"]
