FROM python:3.11-slim AS builder

ENV POETRY_NO_INTERACTION=1 \
    PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1

WORKDIR /build
COPY requirements.txt .
RUN pip install --no-cache-dir --prefix=/install -r requirements.txt

# ── runtime (hardened) ─────────────────────────────────────────────────────────
FROM python:3.11-slim AS runtime

ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    PATH="/usr/local/bin:$PATH"

# Security: only install curl for healthcheck, then remove pkg cache
RUN apt-get update \
    && apt-get install -y --no-install-recommends curl \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/* \
    && rm -f /usr/bin/wget /usr/bin/gcc /usr/bin/make

# Security: create non-root user
RUN groupadd -g 1001 appgroup \
    && useradd -r -u 1001 -g appgroup -s /sbin/nologin -d /app appuser

WORKDIR /app
COPY --from=builder /install /usr/local
COPY app /app/app

# Lock down ownership
RUN chown -R appuser:appgroup /app \
    && chmod -R o-rwx /app

USER appuser

CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "2"]
