# ============================================================
# NSCT — Neutral Search Crawler Tool
# Hardened multi-stage Docker build, non-root user, read-only FS
# ============================================================

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

ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    PIP_NO_CACHE_DIR=1 \
    PIP_DEFAULT_TIMEOUT=60

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

WORKDIR /build

COPY pyproject.toml ./
COPY README.md ./
COPY src/ ./src/
RUN pip install --prefix=/install .

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

ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1

# Minimal packages: curl for health-check, shared libs
RUN apt-get update && apt-get install -y --no-install-recommends \
        curl libpq5 \
    && rm -rf /var/lib/apt/lists/*

# Non-root user
RUN groupadd --gid 1000 nsct && \
    useradd --uid 1000 --gid nsct --shell /bin/sh --create-home nsct

RUN mkdir -p /app/data && chown -R nsct:nsct /app/data

WORKDIR /app

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

RUN chown -R nsct:nsct /app

USER nsct

EXPOSE 8080

CMD ["uvicorn", "nsct.api.main:app", "--host", "0.0.0.0", "--port", "8080"]
