FROM node:18-alpine

WORKDIR /app

# Install curl for health checks
RUN apk add --no-cache curl python3 py3-pip py3-virtualenv

# Ensure shared pipeline schema can be applied automatically when missing
ENV APPLY_SCHEMAS_SQL=true

# Copy package files
COPY package*.json ./

# Install dependencies
RUN npm install

# Copy source code
COPY . .

# Setup Python venv and install AI dependencies if present
RUN if [ -f "/app/ai/requirements.txt" ]; then \
      python3 -m venv /opt/venv && \
      /opt/venv/bin/pip install --no-cache-dir -r /app/ai/requirements.txt; \
    fi

# Ensure venv binaries are on PATH
ENV PATH="/opt/venv/bin:${PATH}"

# Create non-root user
RUN addgroup -g 1001 -S nodejs
RUN adduser -S template-manager -u 1001

# Change ownership
RUN chown -R template-manager:nodejs /app
USER template-manager

# Expose port
EXPOSE 8009 8013

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

# Start the application
CMD ["/bin/sh", "/app/start.sh"]