# =============================================================================
# Go API Server + React SPA (agent-dev / agent-test / agent-main)
# =============================================================================
FROM node:22-bookworm AS web-builder

WORKDIR /web
COPY web/package.json web/package-lock.json* ./
RUN npm ci
COPY web/ ./
RUN npm run build

FROM golang:1.27.1-bookworm AS go-builder

# GOPROXY defaults to the official proxy to preserve upstream build behavior.
# Hosts behind networks that cannot reach proxy.golang.org can pass a
# reachable mirror, e.g. --build-arg GOPROXY=https://goproxy.cn,direct
# (compose wires it from GO_PROXY in the environment env-file).
ARG GOPROXY=https://proxy.golang.org,direct
ENV GOPROXY=${GOPROXY}
ENV GOTOOLCHAIN=auto

WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /server ./cmd/server
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /events ./cmd/events

FROM debian:bookworm-slim

RUN set -eux; \
    apt-get update; \
    apt-get install -y --no-install-recommends ca-certificates curl; \
    rm -rf /var/lib/apt/lists/*

WORKDIR /app
COPY --from=go-builder /server /app/server
COPY --from=go-builder /events /app/events
COPY --from=web-builder /web/dist /app/web/dist
COPY deploy/postgres/goose /app/deploy/postgres/goose
# Official markdown must be on disk at /app/templates/docs and /app/configs.
# .dockerignore keeps *.md out of context except these two trees.
COPY templates /app/templates
COPY configs /app/configs

ENV DATA_DIR=/app/data \
    HTTP_HOST=0.0.0.0 \
    HTTP_PORT=8080

EXPOSE 8080

HEALTHCHECK --interval=10s --timeout=5s --retries=6 \
  CMD curl -fsS "http://127.0.0.1:${HTTP_PORT:-8080}/api/v1/health" || exit 1

ENTRYPOINT ["/app/server"]
CMD ["-env", "/dev/null"]
