# Multi-stage Containerfile - Unified FastAPI + Next.js Frontend
#
# Every stage is Alpine based. The Debian (python:slim) runtime carried a long tail of
# OS packages that nothing in the image used at runtime (util-linux, krb5, ncurses,
# sqlite, perl, systemd libraries, ...) and Debian marks most of their HIGH CVEs as
# won't-fix, so they sat permanently in the Trivy and Grype reports. Alpine ships a far
# smaller base and patches quickly; the Python packages with compiled extensions
# (lxml, pydantic-core) install as musllinux wheels straight from the hash-pinned lock.

# Stage 1: Build Next.js frontend (produces .next/standalone/)
FROM node:26-alpine3.24@sha256:6bd9ab43c0ec0190ca7b2d193906cb8b7edf6e7f4afa43ddeccd6452710bffb5 AS frontend-builder

WORKDIR /frontend

RUN npm install -g npm@12.2.2

# Copy frontend package files
COPY frontend/package.json frontend/package-lock.json* ./

# Install exactly what the lockfile says and skip lifecycle scripts (a common
# supply-chain vector); the lockfile carries the platform-specific optional packages
RUN npm ci --ignore-scripts

# Copy frontend source
COPY frontend/ .

# Build frontend (Next.js standalone output)
RUN npm run build

# Stage 2: Install Python dependencies into a virtual environment
FROM python:3.15-alpine3.24@sha256:0f9552bb28711333da16915ec146f5e6bb44a7fdac9ced15dc17c2e0206346dd AS python-builder

WORKDIR /app

RUN apk upgrade --no-cache

# Create a virtual environment to hold all Python packages
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"

RUN python -m pip install --no-cache-dir "pip==26.3"

# Runtime dependencies come from the hash-pinned lock file: every artifact must match
# a recorded sha256, so a rebuild cannot silently pick up a different or tampered release.
# Everything installs as a wheel (the lock carries the musllinux hashes), so the builder
# needs no compiler.
COPY requirements.txt ./
RUN python -m pip install --no-cache-dir --require-hashes --no-deps -r requirements.txt

# Then install the application itself without re-resolving its dependencies, and prove
# that the lock file satisfies pyproject.toml (pip check fails on anything missing).
# The version comes from the git tag via hatch-vcs; there is no .git in the build
# context, so CI passes it in (APP_VERSION) and local builds get a dev version.
ARG APP_VERSION=0.0.0.dev0
ENV SETUPTOOLS_SCM_PRETEND_VERSION=$APP_VERSION
COPY pyproject.toml README.md ./
COPY backend/ backend/
RUN python -m pip install --no-cache-dir --no-deps . && python -m pip check

# Stage 3: Final runtime image - no build tools, no supervisor
FROM python:3.15-alpine3.24@sha256:0f9552bb28711333da16915ec146f5e6bb44a7fdac9ced15dc17c2e0206346dd

WORKDIR /app

# Runtime packages: nginx for the reverse proxy, plus libstdc++, libgcc and libatomic,
# which the Node.js 26 binary copied in below links against (python:alpine does not
# ship them). curl is deliberately not installed: the health check uses the Python
# interpreter that is already in the image.
RUN apk upgrade --no-cache && apk add --no-cache \
    nginx \
    libstdc++ \
    libgcc \
    libatomic

# python:alpine pulls in sqlite-libs for the stdlib sqlite3 module, which nothing in this
# image imports, and sqlite is a steady source of HIGH CVEs (FTS5, session changesets).
# The base image pins the interpreter's runtime libraries through the .python-rundeps
# virtual package, so re-declare that package without sqlite and apk lets it go.
RUN deps="$(apk info --depends .python-rundeps | tail -n +2 | grep -v '^$' | grep -v sqlite)" \
    && apk add --no-cache --virtual .python-rundeps $deps \
    && apk del --no-cache sqlite-libs \
    && rm -f /usr/local/lib/python3.15/lib-dynload/_sqlite3.*.so \
    && ! apk info -e sqlite-libs

# Unprivileged runtime user. Everything below (nginx, Next.js, gunicorn) runs as this
# user, so the image works with --cap-drop ALL and no-new-privileges.
RUN addgroup -g 10001 app && adduser -D -u 10001 -G app -h /home/app -s /sbin/nologin app

# Copy virtual environment with all Python packages from builder stage
COPY --from=python-builder /opt/venv /opt/venv

# Set PATH to use the virtual environment
ENV PATH="/opt/venv/bin:$PATH"

# Nothing is installed at runtime, so remove the installers from both interpreters.
# pip bundles its own copies of urllib3, msgpack, and other libraries, which image
# scanners report (correctly) as vulnerable packages shipped in the image.
RUN /opt/venv/bin/python -m pip uninstall -y setuptools wheel pip && \
    /usr/local/bin/python -m pip uninstall -y setuptools wheel pip

# Copy application code
# (backend package is installed via pyproject.toml; no separate copy needed)

# Copy Node.js binary from the frontend builder (needed to run Next.js standalone server)
COPY --from=frontend-builder /usr/local/bin/node /usr/local/bin/node

# Copy Next.js standalone application
COPY --from=frontend-builder /frontend/.next/standalone /app/frontend
COPY --from=frontend-builder /frontend/.next/static /app/frontend/.next/static
COPY --from=frontend-builder /frontend/public /app/frontend/public

# nginx configuration. Alpine's nginx.conf includes /etc/nginx/http.d/*.conf inside the
# http context in name order, so the rate-limit zones load first and the site config
# replaces the package's default server.
COPY infra/config/nginx-limits.conf /etc/nginx/http.d/00-limits.conf
COPY infra/config/nginx.conf /etc/nginx/http.d/default.conf

# Copy and enable the entrypoint script
COPY infra/config/docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
RUN chmod +x /usr/local/bin/docker-entrypoint.sh

# nginx as a non-root process: it listens on an unprivileged port (see nginx.conf),
# keeps its pid file in /tmp, and needs its log and temp directories writable. The
# site config stays writable so the entrypoint can substitute the Next.js address.
RUN sed -i 's|^user nginx;|# runs as the unprivileged app user (USER below); no user directive|' /etc/nginx/nginx.conf \
    && sed -i '1i pid /tmp/nginx.pid;' /etc/nginx/nginx.conf \
    && grep -q '^pid /tmp/nginx.pid;' /etc/nginx/nginx.conf \
    && ! grep -q '^user ' /etc/nginx/nginx.conf \
    && mkdir -p /var/log/nginx /app/frontend/.next/cache \
    && ln -sf /dev/stdout /var/log/nginx/access.log && ln -sf /dev/stderr /var/log/nginx/error.log \
    && chown -R app:app /var/log/nginx /var/lib/nginx /run/nginx /etc/nginx/http.d /app/frontend/.next/cache

# Set production environment variables
ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    APP_ENV=production \
    APP_DEBUG=0 \
    RATE_LIMIT_PER_IP=30 \
    RATE_LIMIT_GLOBAL=200 \
    CACHE_DURATION=300 \
    REQUEST_TIMEOUT=15 \
    NEXTJS_PORT=3000 \
    NEXTJS_HOSTNAME=127.0.0.1

# nginx listens on the unprivileged port 8080 and proxies both the frontend and the API.
# Map it with -p <host>:8080.
EXPOSE 8080

USER app

# Health check (urlopen raises on any non-2xx response, so a failing probe exits non-zero)
HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \
    CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/api/v1/health/ready', timeout=5)" || exit 1

# Use the entrypoint script to start nginx + gunicorn (replaces supervisor)
ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]
