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

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

WORKDIR /app

# ✅ 必须在 COPY 前存在 lock 文件，确保版本一致
COPY pnpm-lock.yaml ./
COPY pnpm-workspace.yaml ./
COPY package.json ./

RUN npm install -g pnpm

COPY . ./

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

# ✅ 安装所有 workspace 的依赖，包含 apps/blogai 的 next 等
RUN pnpm install --frozen-lockfile --recursive

WORKDIR /app/apps/blogai
RUN pnpm run build


# --- 第二阶段：运行阶段 ---
FROM node:20-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/

# 拷贝 blogai 应用产物
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"]
