# Chatc2 — Dockerfile
# Multi-stage: build (whisper.cpp compilação) + runtime (Node + Firebird client)
#
# Build:
#   docker build -t chatc2 .
#
# Run (com docker-compose):
#   docker compose up -d

# ============================================================
# STAGE 1: Compilar whisper.cpp
# ============================================================
FROM alpine:3.20 AS whisper-builder

RUN apk add --no-cache git make g++ cmake

WORKDIR /build
RUN git clone --depth 1 https://github.com/ggerganov/whisper.cpp.git && \
    cd whisper.cpp && \
    cmake -B build && \
    cmake --build build --config Release -j $(nproc)

# Baixa modelo tiny
RUN cd /build/whisper.cpp && \
    mkdir -p models && \
    wget -q -O models/ggml-tiny.bin https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-tiny.bin

# ============================================================
# STAGE 2: Runtime Node.js
# ============================================================
FROM node:22-alpine

# Dependências do sistema: Firebird client, ffmpeg
RUN apk add --no-cache \
    firebird-dev \
    ffmpeg \
    cmake \
    make \
    g++ \
    python3

WORKDIR /app

# Copia package.json e instala dependências
COPY package.json package-lock.json ./
RUN npm ci --omit=dev && npm cache clean --force

# Copia código fonte
COPY src/ ./src/
COPY scripts/ ./scripts/
COPY public/ ./public/

# Copia whisper.cpp compilado e modelo
COPY --from=whisper-builder /build/whisper.cpp/build/bin/main /app/whisper/main
COPY --from=whisper-builder /build/whisper.cpp/models/ggml-tiny.bin /app/whisper/models/ggml-tiny.bin

# Copia configuração PM2
COPY ecosystem.config.js ./

# Diretórios de runtime
RUN mkdir -p /app/db /app/logs /app/uploads/audio /app/tmp

# Variáveis padrão (sobrescrever no docker-compose ou .env)
ENV PORT=3000 \
    NODE_ENV=production \
    DB_HOST=firebird \
    DB_PORT=3050 \
    DB_DATABASE=/app/db/NOVO.FDB \
    DB_USER=SYSDBA \
    DB_PASSWORD=masterkey

EXPOSE 3000

# Healthcheck
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
  CMD wget -qO- http://localhost:3000/api/novo_local/health || exit 1

CMD ["node", "src/server.js"]
