# syntax=docker/dockerfile:1
#
# Base images are pinned to the project's registry mirrors so the build is
# deterministic and avoids Docker Hub / ghcr.io pull failures in CN networks.
# Trade-off: `docker build .` requires reachability of these registries.
#
#   NPM_REGISTRY    – npm registry for `npm ci` (build-arg)
#   APT_MIRROR      – Debian apt mirror host (build-arg, empty = official)
#   UV_INDEX_URL    – PyPI index URL passed through to `uv sync` (build-arg, empty = official)

# Stage 1: build the cloud-console Vue 3 SPA.
# NOTE: do not set NODE_ENV=production here — vue-tsc and typescript are
# devDependencies required by `npm run build`.
ARG NPM_REGISTRY=https://registry.npmjs.org
FROM registry.jerryyan.top/library/node:20-bookworm-slim AS frontend
# Re-declare inside the stage so --build-arg values (or the global default)
# are visible to RUN. Without this, ARGs declared before FROM are inaccessible.
ARG NPM_REGISTRY
WORKDIR /app
COPY cloud-console/package.json cloud-console/package-lock.json ./
RUN npm ci --registry=${NPM_REGISTRY}
COPY cloud-console/ ./
RUN npm run build

# Stage 2: the existing Python image, now carrying the SPA build output.
FROM registry-ghcr.jerryyan.top/astral-sh/uv:python3.13-bookworm-slim

ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    UV_COMPILE_BYTECODE=1 \
    UV_LINK_MODE=copy

WORKDIR /app

ARG APT_MIRROR=
# bookworm uses /etc/apt/sources.list.d/debian.sources (DEB822 format); older
# Debian releases use /etc/apt/sources.list. Patch whichever exists.
RUN if [ -n "$APT_MIRROR" ]; then \
        if [ -f /etc/apt/sources.list.d/debian.sources ]; then \
            sed -i "s|deb.debian.org|$APT_MIRROR|g; s|security.debian.org|$APT_MIRROR|g" \
                /etc/apt/sources.list.d/debian.sources; \
        elif [ -f /etc/apt/sources.list ]; then \
            sed -i "s|deb.debian.org|$APT_MIRROR|g; s|security.debian.org|$APT_MIRROR|g" \
                /etc/apt/sources.list; \
        fi; \
    fi \
    && apt-get update && apt-get install -y --no-install-recommends curl \
    && rm -rf /var/lib/apt/lists/*

COPY --from=frontend /app/dist /app/console-static
COPY . .

ARG UV_INDEX_URL=
ENV UV_INDEX_URL=${UV_INDEX_URL}
RUN uv sync --locked --all-packages --no-dev

ENV PATH="/app/.venv/bin:$PATH" \
    CLOUD_CONSOLE_STATIC_DIR=/app/console-static

CMD ["device-cloud-api", "--host", "0.0.0.0", "--port", "8001"]
