# syntax=docker/dockerfile:1
#
# In production pin both FROM lines by digest for reproducible, tamper-evident builds (review L14):
#   FROM python:3.12-slim@sha256:<digest>
# Resolve the digest against the registry at build time, e.g.
#   docker buildx imagetools inspect python:3.12-slim

# ── build stage: resolve dependencies, including the private one ─────────────
# `dredd-core` is a private repository on the Haski Gitea pinned by tag in requirements.txt, so installing it
# needs two things the runtime image should never have: `git` (python:3.12-slim ships none) and a
# credential.
#
# The credential arrives as a BuildKit SECRET, not a build argument. A build arg is baked into the
# image history — `docker history` prints it — so a pushed image would publish the token to anyone
# who can pull it. A secret mount exists only for the duration of the one RUN that uses it.
# `GIT_CONFIG_*` scopes the rewrite to that same process, so nothing is written to a gitconfig
# that could survive into a layer either.
#
# Build with:  DREDD_CORE_TOKEN=... docker compose build     (compose passes it as the secret)
# (The same secret handling as Galena's and Atrium's.)
FROM python:3.12-slim AS build

ENV PIP_NO_CACHE_DIR=1 \
    PIP_DISABLE_PIP_VERSION_CHECK=1

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

WORKDIR /build

# pg8000 is a pure-Python driver — no system libraries (libpq) required.

COPY requirements.txt .
# `required=true` only fails when the secret is ABSENT — compose passes an unset DREDD_CORE_TOKEN as
# an EMPTY secret, which would otherwise surface much later as a confusing git auth error. Hence the
# `test -s`. `tr -d` drops a stray CR/LF from a pasted token (git would echo a key containing one).
RUN --mount=type=secret,id=dredd_core_token,required=true \
    test -s /run/secrets/dredd_core_token \
      || { echo "build secret dredd_core_token is empty - export DREDD_CORE_TOKEN" >&2; exit 1; }; \
    GIT_CONFIG_COUNT=1 \
    GIT_CONFIG_KEY_0="url.http://x-access-token:$(tr -d '\r\n' < /run/secrets/dredd_core_token)@77.216.148.202:3000/.insteadOf" \
    GIT_CONFIG_VALUE_0="http://77.216.148.202:3000/" \
    pip install --prefix=/install -r requirements.txt

# ── runtime stage: no git, no credential ─────────────────────────────────────
FROM python:3.12-slim

ENV PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1 \
    PIP_NO_CACHE_DIR=1 \
    PIP_DISABLE_PIP_VERSION_CHECK=1

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

WORKDIR /app

COPY . .

# The static console, which this backend now serves itself (app/main.py mounts it at "/"; nothing
# stands in front of it). It lives in the repo's frontend/, outside this build context, so it
# arrives as a NAMED build context: compose passes `additional_contexts: { frontend: ./frontend }`,
# and a bare build from backend/ needs `docker build --build-context frontend=../frontend .`.
# /frontend is exactly where main.py's default (two levels above app/main.py) looks.
COPY --from=frontend . /frontend

# Install the backend as a package so `import app` works regardless of cwd. It declares no
# dependencies of its own (requirements.txt, above, holds them all), so this needs no git or token.
RUN pip install -e .

# Run as non-root.
RUN useradd --create-home --uid 10001 appuser \
    && chown -R appuser:appuser /app
USER appuser

EXPOSE 8000

# The path prefix the reverse proxy strips before the request reaches us: ROOT_PATH=/counsel when
# Counsel runs as a module of the platform (one origin, one module per path), empty — the default
# here — when it is served at the origin root. uvicorn PREPENDS it to the incoming path, so it pairs
# with the front door stripping /counsel (Atrium forwards `/counsel/*` without it): set one without
# the other and you get either a doubled prefix (404 everywhere) or server-generated URLs that
# escape the prefix. app/config.py reads the same variable, so FastAPI's root_path always agrees
# with uvicorn's.
ENV ROOT_PATH=

# Which proxy may set X-Forwarded-For / -Proto. On the platform that is Atrium's front door, pinned to
# Counsel's network in Atrium's compose.yaml; standalone nothing sits in front, so the default trusts
# loopback only (an empty value means the same — `:-` treats empty as unset). deps.client_ip reads
# request.client, which uvicorn's --proxy-headers has already resolved from a trusted hop only.
ENV FORWARDED_ALLOW_IPS=

# `sh -c` so $ROOT_PATH / $FORWARDED_ALLOW_IPS expand at start-up rather than being baked in at build
# time; `exec` so uvicorn replaces the shell and still gets SIGTERM directly on `docker compose stop`
# (without it the shell holds PID 1, swallows the signal, and every stop waits out the 10s kill
# timeout). --no-server-header: nothing stands in front of uvicorn to strip `Server`.
CMD ["sh", "-c", "exec uvicorn app.main:app --host 0.0.0.0 --port 8000 --root-path \"$ROOT_PATH\" --proxy-headers --forwarded-allow-ips \"${FORWARDED_ALLOW_IPS:-127.0.0.1}\" --no-server-header"]
