# Test Dockerfile - Go components only
FROM golang:1.25-alpine AS builder

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

# Set working directory
WORKDIR /app

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

# Download dependencies
RUN go mod download

# Copy source code
COPY . .

# Build only Go binaries (skip Zig)
RUN CGO_ENABLED=1 go build -o bin/api-server cmd/api-server/main.go && \
    go build -o bin/worker cmd/worker/worker_server.go cmd/worker/worker_config.go && \
    go build -o bin/tui ./cmd/tui

# Final stage
FROM alpine:3.19

# Install runtime dependencies
RUN apk add --no-cache ca-certificates curl openssl

# Create app user
RUN addgroup -g 1001 -S appgroup && \
    adduser -u 1001 -S appuser -G appgroup

# Set working directory
WORKDIR /app

# Copy binaries from builder
COPY --from=builder /app/bin/ /usr/local/bin/

# Copy configs
COPY --from=builder /app/configs/ /app/configs/

# Create necessary directories
RUN mkdir -p /app/data/experiments /app/data/datasets /app/data/snapshots /app/logs /app/ssl && \
    mkdir -p /data/experiments /data/datasets /data/snapshots

# Generate SSL certificates for container use
RUN openssl req -x509 -newkey rsa:2048 -keyout /app/ssl/key.pem -out /app/ssl/cert.pem -days 365 -nodes \
    -subj "/C=US/ST=Test/L=Local/O=FetchML/OU=Tests/CN=localhost" && \
    chmod 644 /app/ssl/cert.pem && chmod 600 /app/ssl/key.pem

# Ensure app user can write to data/logs and read TLS material
RUN chown -R appuser:appgroup /app/data /app/logs /app/ssl /app/configs /data

# Switch to app user
USER appuser

# Expose ports
EXPOSE 9101

# Default command
CMD ["/usr/local/bin/api-server", "-config", "/app/configs/api/dev.yaml"]
