# ── 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.
FROM 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 wheels for
# linux/amd64 on py3.12.
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"]
