# Multi-stage Dockerfile - Unified FastAPI + Next.js Frontend
# Stage 1: Build Next.js frontend (produces .next/standalone/)
FROM node:26-trixie-slim@sha256:e6bedef217677b276c591795e169840edd9096dbf13f29df8ef8d1856b8820bc 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: Build Python dependencies (requires gcc for compiled extensions)
FROM python:3.15-slim-trixie@sha256:65a65fc7b30b06cb6df4930fd4650697cb23f4c2698ab81fc87e4b031bc36928 AS python-builder

WORKDIR /app

# Install build-only tools (not copied to final image)
RUN apt-get update && apt-get upgrade -y && apt-get install -y --no-install-recommends gcc && \
    apt-get clean && rm -rf /var/cache/apt/archives/* /var/lib/apt/lists/*

# 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.
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-slim-trixie@sha256:65a65fc7b30b06cb6df4930fd4650697cb23f4c2698ab81fc87e4b031bc36928

WORKDIR /app

# Install runtime dependencies: nginx for the reverse proxy and libatomic1, which the
# Node.js 26 binary copied in below links against (python:slim does not ship it).
# curl is deliberately not installed: the health check uses the Python interpreter
# that is already in the image, and curl/libcurl carried the largest share of
# (unfixed) OS vulnerability findings in container scans.
RUN apt-get update && apt-get upgrade -y && apt-get install -y --no-install-recommends \
    nginx \
    libatomic1 \
    && apt-get clean && rm -rf /var/cache/apt/archives/* /var/lib/apt/lists/*

# 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 groupadd --gid 10001 app && useradd --uid 10001 --gid app --create-home --shell /usr/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

# Copy nginx configuration (site config plus the http-level rate limit zones)
COPY infra/config/nginx.conf /etc/nginx/sites-available/default
COPY infra/config/nginx-limits.conf /etc/nginx/conf.d/limits.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|^pid /run/nginx.pid;|pid /tmp/nginx.pid;|; s|^user www-data;|# runs as the unprivileged app user (USER below); no user directive|' /etc/nginx/nginx.conf \
    && grep -q '^pid /tmp/nginx.pid;' /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 /etc/nginx/sites-available /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"]
