# Multi-stage build for minimal image size

# Stage 1: Build
FROM golang:1.21-alpine AS builder

# Install build dependencies
RUN apk add --no-cache git make

WORKDIR /build

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

# Copy source code
COPY . .

# Build the binary
RUN CGO_ENABLED=0 GOOS=linux go build \
    -ldflags="-s -w" \
    -o ide \
    ./cmd/ide

# Install gopls (LSP server)
RUN go install golang.org/x/tools/gopls@latest

# Stage 2: Runtime
FROM alpine:latest

# Install runtime dependencies
RUN apk add --no-cache \
    ca-certificates \
    git \
    bash

# Create non-root user
RUN addgroup -S ideuser && adduser -S ideuser -G ideuser

WORKDIR /app

# Copy binary from builder
COPY --from=builder /build/ide /app/ide
COPY --from=builder /go/bin/gopls /usr/local/bin/gopls

# Copy embedded assets
COPY --from=builder /build/web/dist /app/web/dist

# Create workspace directory
RUN mkdir -p /workspace && chown -R ideuser:ideuser /workspace /app

# Switch to non-root user
USER ideuser

# Expose port
EXPOSE 3000

# Set environment variables
ENV PORT=3000
ENV WORKSPACE=/workspace

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

# Run the IDE
ENTRYPOINT ["/app/ide"]
CMD ["--workspace=/workspace", "--port=3000"]
