# Build stage
ARG GO_IMAGE_TAG=1.25.8-bookworm
FROM golang:${GO_IMAGE_TAG} AS builder
ARG REMBG_ENABLED=true

WORKDIR /app

# Install build dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
    git \
    build-essential \
    && if [ "$REMBG_ENABLED" = "true" ]; then apt-get install -y --no-install-recommends python3 python3-pip python3-dev; fi \
    && rm -rf /var/lib/apt/lists/*

# Download Go dependencies
COPY go.mod go.sum ./
RUN go mod download

# Copy source code
COPY . .

# Install Python dependencies for rembg
COPY scripts/requirements-rembg.txt .
RUN --mount=type=cache,target=/root/.cache/pip \
    if [ "$REMBG_ENABLED" = "true" ]; then pip3 install --break-system-packages -r requirements-rembg.txt; else echo "REMBG disabled, skipping pip install"; fi

# Build the application
RUN CGO_ENABLED=0 GOOS=linux go build -o fotbal-club

# Final stage
FROM debian:bullseye-slim
ARG REMBG_ENABLED=true

WORKDIR /app

# Install runtime dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
    ca-certificates \
    tzdata \
    && if [ "$REMBG_ENABLED" = "true" ]; then apt-get install -y --no-install-recommends python3 python3-pip python3-dev libgl1-mesa-glx libglib2.0-0; fi \
    && rm -rf /var/lib/apt/lists/*

# Create non-root user
RUN addgroup --system app && adduser --system --ingroup app app \
    && mkdir -p /app/uploads /app/cache \
    && chown -R app:app /app

# Install rembg and its dependencies
COPY --from=builder /app/requirements-rembg.txt .
RUN --mount=type=cache,target=/root/.cache/pip \
    if [ "$REMBG_ENABLED" = "true" ]; then pip3 install --break-system-packages -r requirements-rembg.txt; fi \
    && rm -f requirements-rembg.txt

# Copy the binary from builder
COPY --from=builder /app/fotbal-club ./fotbal-club

# Copy templates and static files if any
COPY ./templates ./templates
COPY ./static ./static

# Environment and permissions
ENV GIN_MODE=release
USER app

# Expose port
EXPOSE 8080

# Healthcheck: use busybox wget to probe liveness/readiness
HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 \
  CMD wget -q -O - http://127.0.0.1:8080/api/v1/health >/dev/null 2>&1 || exit 1

# Command to run the executable
CMD ["./fotbal-club"]
