# Build stage
FROM golang:1.24-alpine AS builder

# Set working directory
WORKDIR /app

# Install dependencies
RUN apk add --no-cache git ca-certificates tzdata

# Copy go mod files
COPY go.mod go.sum ./

# Set Go environment variables and proxy
ENV GO111MODULE=on \
  CGO_ENABLED=0 \
  GOOS=linux \
  GOARCH=amd64 \
  GOPROXY=https://goproxy.cn,https://goproxy.io,direct \
  GOSUMDB=sum.golang.google.cn

# Download dependencies with retry mechanism
RUN go mod download || \
  (echo "Retrying with different proxy..." && \
  go env -w GOPROXY=https://goproxy.io,https://mirrors.aliyun.com/goproxy/,direct && \
  go mod download) || \
  (echo "Final retry with direct mode..." && \
  go env -w GOPROXY=direct && \
  go mod download)

# Copy source code
COPY . .

# Build the application
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -a -ldflags '-w -s' -trimpath -o miniChat .

# Final stage
FROM alpine:latest

# Install ca-certificates for HTTPS requests
RUN apk --no-cache add ca-certificates tzdata

# Set timezone
ENV TZ=Asia/Shanghai

# Create app directory
WORKDIR /app

# Copy binary from builder stage
COPY --from=builder /app/miniChat .

# Copy configuration files if they exist
COPY --from=builder /app/configs ./configs

# Create logs directory
RUN mkdir -p /app/logs

# Expose port
EXPOSE 9991

# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD wget --no-verbose --tries=1 --spider http://localhost:9991/system/health || exit 1

# Run the application
CMD ["sh", "-c", "./miniChat -env=${ACTIVE_ENV}"]