# syntax=docker/dockerfile:1
#
# Build args let CI inject mirrors for faster builds in CN networks; the
# defaults keep the Dockerfile portable so anyone can `docker build .`
# without extra configuration.
#
#   NODE_IMAGE      – stage 1 base (Docker Hub library/node)
#   NPM_REGISTRY    – npm registry for `npm ci`
#   UV_IMAGE        – stage 2 base (ghcr.io/astral-sh/uv)
#   APT_MIRROR      – Debian apt mirror host (e.g. mirrors.aliyun.com); empty = official
#   UV_INDEX_URL    – PyPI index URL passed through to `uv sync`; 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 NODE_IMAGE=node:20-bookworm-slim
ARG NPM_REGISTRY=https://registry.npmjs.org
FROM ${NODE_IMAGE} 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.
ARG UV_IMAGE=ghcr.io/astral-sh/uv:python3.14-bookworm-slim
FROM ${UV_IMAGE}

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"

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