# ═══════════════════════════════════════════════════════════
# 🐍 OPHION - Dockerfile All-in-One
# Imagem única com Server + Agent + Dashboard
# ═══════════════════════════════════════════════════════════

# ─────────────────────────────────────────────────────────────
# Stage 1: Build Go binaries
# ─────────────────────────────────────────────────────────────
FROM golang:1.22-alpine AS go-builder

WORKDIR /build

# Dependências
RUN apk add --no-cache git ca-certificates

# Go modules
COPY go.mod go.sum ./
RUN go mod download

# Código fonte
COPY cmd/ ./cmd/
COPY internal/ ./internal/

# Build server
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \
    go build -ldflags="-s -w" -o ophion-server ./cmd/server

# ─────────────────────────────────────────────────────────────
# Stage 2: Build Dashboard (Next.js)
# ─────────────────────────────────────────────────────────────
FROM node:20-alpine AS web-builder

WORKDIR /build

# Dependências
COPY dashboard/package*.json ./
RUN npm install

# Código fonte
COPY dashboard/ ./

# Build
ENV NEXT_TELEMETRY_DISABLED=1
RUN npm run build

# ─────────────────────────────────────────────────────────────
# Stage 3: Runtime Image
# ─────────────────────────────────────────────────────────────
FROM alpine:3.19

LABEL org.opencontainers.image.title="OPHION"
LABEL org.opencontainers.image.description="Open Source Observability Platform"
LABEL org.opencontainers.image.source="https://github.com/bigtux/ophion"
LABEL org.opencontainers.image.vendor="OPHION"
LABEL org.opencontainers.image.licenses="AGPL-3.0"

# Dependências runtime
RUN apk add --no-cache \
    ca-certificates \
    tzdata \
    nodejs \
    npm \
    supervisor \
    curl \
    bash

# Criar usuário não-root
RUN addgroup -g 1000 ophion && \
    adduser -u 1000 -G ophion -s /bin/sh -D ophion

WORKDIR /app

# Copiar binários Go
COPY --from=go-builder /build/ophion-server /app/bin/

# Copiar Dashboard
COPY --from=web-builder /build/.next /app/web/.next
COPY --from=web-builder /build/public /app/web/public
COPY --from=web-builder /build/package*.json /app/web/
COPY --from=web-builder /build/node_modules /app/web/node_modules

# Configs
COPY configs/ /app/configs/
COPY web/ /app/static/

# Supervisor config
RUN mkdir -p /etc/supervisor.d
COPY deploy/docker/supervisord.conf /etc/supervisor.d/ophion.ini

# Diretórios
RUN mkdir -p /app/data /app/logs && \
    chown -R ophion:ophion /app

# Script de entrada
COPY deploy/docker/entrypoint.sh /app/
RUN chmod +x /app/entrypoint.sh

# Portas
EXPOSE 8080 3000

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=10s --retries=3 \
    CMD curl -f http://localhost:8080/health || exit 1

# Variáveis de ambiente padrão
ENV TZ=America/Sao_Paulo \
    LOG_LEVEL=info \
    SERVER_PORT=8080 \
    DASHBOARD_PORT=3000

USER ophion

ENTRYPOINT ["/app/entrypoint.sh"]
CMD ["all"]
