# ---- Build stage ----
FROM python:3.12-slim AS builder

WORKDIR /build

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

COPY pyproject.toml .
RUN pip install --no-cache-dir .

# ---- Runtime stage ----
FROM python:3.12-slim

WORKDIR /app

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

RUN groupadd -r scilit && useradd -r -g scilit -d /app -s /sbin/nologin scilit

COPY --from=builder /usr/local /usr/local

COPY . .
RUN chown -R scilit:scilit /app

USER scilit

HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
    CMD curl -sf http://localhost:8000/health || exit 1

CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "4", "--proxy-headers", "--forwarded-allow-ips", "127.0.0.1,172.0.0.0/8,10.0.0.0/8", "--limit-concurrency", "256", "--timeout-keep-alive", "30", "--log-level", "warning"]
