# --- 第一阶段：构建阶段 ---
FROM node:18-bullseye-slim AS builder

ARG BLOGAI_HOST=ai.szaiai.com
ENV NODE_ENV=production
ENV BLOGAI_HOST=${BLOGAI_HOST}

WORKDIR /app

RUN npm install -g pnpm

COPY . ./

COPY apps/blogai/.env.example apps/blogai/.env
RUN sed -i "s|{{BLOGAI_HOST}}|${BLOGAI_HOST}|g" apps/blogai/.env

RUN pnpm install

WORKDIR /app/apps/blogai
RUN pnpm run build


# --- 第二阶段：运行阶段 ---
FROM node:18-slim AS runner

ARG BLOGAI_HOST=ai.szaiai.com
ENV NODE_ENV=production
ENV PORT=3008
ENV BLOGAI_HOST=${BLOGAI_HOST}

# 安装 supervisor
RUN apt-get update && \
    apt-get install -y supervisor  curl && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*

# 设置 supervisor 配置目录
RUN mkdir -p /etc/supervisor/conf.d

# 设置工作目录
WORKDIR /plugai

# 拷贝 supervisor.conf 到指定路径
COPY ./supervisor.conf /etc/supervisor/conf.d/supervisor.conf

# 拷贝 node_modules
COPY --from=builder /app/node_modules ./node_modules

WORKDIR /plugai/zerostack/t1/

COPY --from=builder /app/apps/blogai/package.json ./package.json
COPY --from=builder /app/apps/blogai/node_modules ./node_modules
COPY --from=builder /app/apps/blogai/.next ./.next
COPY --from=builder /app/apps/blogai/public ./public
COPY --from=builder /app/apps/blogai/next.config.js ./next.config.js
COPY --from=builder /app/apps/blogai/next-i18next.config.js ./next-i18next.config.js

# 确保 wrapper.sh 可执行权限
COPY ./wrapper.sh /plugai/wrapper.sh
RUN chmod +x /plugai/wrapper.sh

RUN rm -rf /root/.npm /root/.pnpm-store /tmp/*

HEALTHCHECK --interval=30s --timeout=3s --start-period=25s --retries=3 CMD curl -fs http://localhost:3008/api/health/ || exit 1

EXPOSE 3008


# 使用 supervisor 启动
CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/conf.d/supervisor.conf"]
