# Build stage
FROM golang:1.24-alpine AS builder

ENV GOTOOLCHAIN=auto

# Install build dependencies for SQLite3
RUN apk add --no-cache git gcc musl-dev

WORKDIR /app

# Copy go mod files
COPY server/go.mod server/go.sum ./
RUN go mod download

# Copy source code
COPY server/ ./
COPY agent/ ../agent/

# Build server with CGO enabled for SQLite3
RUN CGO_ENABLED=1 GOOS=linux go build -ldflags="-s -w -linkmode external -extldflags '-static'" -o /nuyue-server ./cmd/server

# Build agent (no CGO needed)
RUN cd ../agent && CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /nuyue-agent ./cmd/agent

# Runtime stage
FROM alpine:3.19

RUN apk add --no-cache ca-certificates tzdata

WORKDIR /app

# Copy binaries
COPY --from=builder /nuyue-server /app/
COPY --from=builder /nuyue-agent /app/

# Copy frontend (built by CI)
COPY server/embed/dist /app/embed/dist

# Expose ports
EXPOSE 8080 9090

# Run server
CMD ["/app/nuyue-server"]
