# ── stage 1: build the UI ───────────────────────────────────────────────
#
# Next.js is a BUILD-time dependency only. `output: "export"` emits plain
# HTML/JS/CSS, so Node never runs in the final image and the runtime stays a
# single Python process — same container, same healthcheck, same everything
# the deploy already expects.
#
# --platform=$BUILDPLATFORM pins this stage to the NATIVE architecture of
# whatever is doing the building, instead of the architecture being built
# FOR. That matters now that this image is multi-arch: without it, the arm64
# image would run `npm ci` and `npm run build` under QEMU emulation, which is
# by far the slowest thing in this file — several minutes, repeated per
# platform.
#
# It is safe precisely because the output is static HTML/JS/CSS. There is no
# native code in `out/`, so bytes built on amd64 are byte-identical to bytes
# built on arm64, and stage 2 just copies them in.
FROM --platform=$BUILDPLATFORM node:22-slim AS web

WORKDIR /web

# Copied separately so editing a component doesn't re-run npm ci.
COPY web/package.json web/package-lock.json ./
RUN npm ci

COPY web/ ./
RUN npm run build


# ── stage 2: runtime ────────────────────────────────────────────────────
#
# Slim, no build toolchain needed — every Python dependency ships prebuilt
# wheels on py3.12 for BOTH linux/amd64 and linux/arm64. fastapi, httpx and
# mutagen are pure Python; uvicorn[standard]'s compiled extras (uvloop,
# httptools, watchfiles) all publish aarch64 manylinux wheels.
#
# That is what keeps the emulated arm64 build cheap: pip downloads wheels
# rather than invoking a compiler under QEMU. If a dependency is ever added
# that has no aarch64 wheel, this build will suddenly take ten minutes and
# need gcc — that is the signal to switch to a native arm64 runner.
FROM python:3.12-slim

WORKDIR /app

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY app.py .
COPY --from=web /web/out ./web/out

# Runs as 1000:1000 via the compose `user:` key, matching every other
# container that touches /data. Nothing here needs root.
EXPOSE 5040

HEALTHCHECK --interval=60s --timeout=10s --start-period=15s --retries=3 \
  CMD python -c "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:5040/healthz',timeout=8).status==200 else 1)"

CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "5040", "--no-access-log"]
