# 多阶段构建 Dockerfile - 前后端一体化部署
# 阶段1: 构建前端
FROM node:18-alpine as frontend-builder

WORKDIR /app/web

# 复制前端依赖文件
COPY web/package*.json ./

# 安装依赖
RUN npm install --registry=https://registry.npmmirror.com

# 复制前端源码
COPY web/ ./

# 构建前端
RUN npm run build

# 阶段2: 构建后端
FROM golang:1.23-alpine as backend-builder

# 设置环境变量允许 Go 自动下载工具链
ENV GO111MODULE=on \
    GOPROXY=https://goproxy.cn,direct \
    CGO_ENABLED=0 \
    GOTOOLCHAIN=auto

WORKDIR /app/server

# 复制后端依赖文件
COPY server/go.mod server/go.sum ./

# 下载依赖
RUN go mod download

# 复制后端源码
COPY server/ ./

# 构建后端
RUN go build -ldflags="-s -w" -o ai_proxy .

# 阶段3: 最终镜像
FROM alpine:latest

LABEL maintainer="AI Proxy Team"
LABEL description="AI Proxy - 前后端一体化部署"

# 设置时区
ENV TZ=Asia/Shanghai
RUN apk update && apk add --no-cache tzdata ca-certificates \
    && ln -sf /usr/share/zoneinfo/$TZ /etc/localtime \
    && echo $TZ > /etc/timezone

WORKDIR /app

# 从构建阶段复制文件
COPY --from=backend-builder /app/server/ai_proxy ./
COPY --from=backend-builder /app/server/resource ./resource/
COPY --from=frontend-builder /app/web/dist ./dist/

# 复制配置文件（如果有 config.docker.yaml）
COPY server/config.docker.yaml ./config.yaml

# 创建必要的目录
RUN mkdir -p uploads/file log data

# 暴露端口
EXPOSE 8989

# 健康检查
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD wget --no-verbose --tries=1 --spider http://localhost:8989/api/health || exit 1

# 启动应用
ENTRYPOINT ["./ai_proxy"]
