# ============================================
# Stage 1: Build frontend + compile backend
# ============================================
FROM node:20-alpine AS builder

WORKDIR /app

# Install zip for skill packaging
RUN apk add --no-cache zip bash

# Copy package files first for better caching
COPY package*.json ./

# Install all dependencies (including dev deps for build)
RUN npm ci

# Copy source code
COPY . .

# Vite env vars for analytics (injected at build time, values from .env on server)
ARG VITE_UMAMI_ID
ARG VITE_UMAMI_SRC
ARG VITE_UMAMI_HOST
ENV VITE_UMAMI_ID=$VITE_UMAMI_ID
ENV VITE_UMAMI_SRC=$VITE_UMAMI_SRC
ENV VITE_UMAMI_HOST=$VITE_UMAMI_HOST

# Build skill zip package (outputs to public/watchitai-skill.zip)
RUN bash skill/build.sh

# Build frontend (vite build, copies public/ including skill zip to dist/)
RUN npm run build:app

# Compile backend TypeScript to JavaScript
RUN npx tsc -p tsconfig.api.json

# ============================================
# Stage 2: Production image
# ============================================
FROM node:20-alpine AS runner

WORKDIR /app

ENV NODE_ENV=production
ENV PORT=3001

# Copy package files
COPY package*.json ./

# Install only production dependencies
RUN npm ci --omit=dev

# Copy built frontend assets from builder stage
COPY --from=builder /app/dist ./dist

# Copy compiled backend from builder stage
COPY --from=builder /app/dist-api ./dist-api

# Expose port
EXPOSE 3001

# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
  CMD wget --no-verbose --tries=1 --spider http://localhost:3001/api/health || exit 1

# Run compiled server
CMD ["node", "dist-api/server.js"]
