ARG NODE_IMAGE=docker.1panel.live/library/node:24-alpine
ARG GO_IMAGE=docker.1panel.live/library/golang:1.26-alpine
ARG ALPINE_IMAGE=docker.1panel.live/library/alpine:3.23

FROM ${NODE_IMAGE} AS frontend
ARG NPM_REGISTRY=auto
WORKDIR /src/web
COPY web/package*.json ./
RUN if [ "${NPM_REGISTRY}" = auto ]; then \
      npm ci --registry=https://registry.npmjs.org --fetch-retries=0 --fetch-timeout=15000 \
      || { echo 'Retrying npm install with npmmirror'; npm ci --registry=https://registry.npmmirror.com --fetch-retries=1 --fetch-timeout=30000; }; \
    else npm ci --registry="${NPM_REGISTRY}"; fi
COPY web/ ./
RUN npm run build

FROM ${GO_IMAGE} AS backend
ARG GOPROXY=https://proxy.golang.org|https://goproxy.cn|direct
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
COPY --from=frontend /src/web/dist ./web/dist
RUN CGO_ENABLED=0 go build -trimpath -ldflags='-s -w' -o /ai-router .

FROM ${ALPINE_IMAGE}
ARG ALPINE_MIRROR=auto
RUN set -eu; \
    if [ "${ALPINE_MIRROR}" = auto ]; then \
      apk --timeout 15 add --no-cache ca-certificates \
      || { echo 'Retrying apk install with Aliyun mirror'; \
           sed -i 's|https\?://dl-cdn.alpinelinux.org/alpine|https://mirrors.aliyun.com/alpine|g' /etc/apk/repositories; \
           apk --timeout 30 add --no-cache ca-certificates; }; \
    else \
      sed -i "s|https\?://dl-cdn.alpinelinux.org/alpine|${ALPINE_MIRROR%/}|g" /etc/apk/repositories; \
      apk add --no-cache ca-certificates; \
    fi; \
    addgroup -g 10001 router; adduser -D -u 10001 -G router router
WORKDIR /app
RUN mkdir /app/data && chown router:router /app/data
COPY --from=backend /ai-router /usr/local/bin/ai-router
USER router
EXPOSE 8080
ENTRYPOINT ["ai-router", "-config", "/app/config.yaml"]
