# Stage 1: Node.js for TailwindCSS build
FROM node:16-alpine as tailwind-builder

# Set working directory for Tailwind build
WORKDIR /app

# Copy only the necessary files for TailwindCSS build
COPY package.json package-lock.json ./
COPY ./app/templates ./app/templates
COPY ./app/static/js ./app/static/js
COPY ./app/static/css/input.css ./app/static/css/input.css
COPY ./scripts/check-assets.cjs ./scripts/check-assets.cjs
COPY tailwind.config.js ./

# Install Node.js dependencies
RUN npm install

# Set NODE_ENV to production and build TailwindCSS assets
ENV NODE_ENV=production
RUN npm run build

# Stage 2: Python for Flask app
FROM python:3.9-slim

# Install system dependencies
RUN apt-get update && apt-get install -y \
    build-essential \
    libpq-dev \
    && rm -rf /var/lib/apt/lists/*

# Set working directory for Flask app
WORKDIR /app

# Copy only necessary application files
COPY requirements.txt ./

# Install Python dependencies
RUN pip install --no-cache-dir -r requirements.txt

# Copy the rest of the application files
COPY . .

# Copy the built TailwindCSS assets from the first stage
COPY --from=tailwind-builder /app/app/static/css/tailwind.css ./app/static/css/tailwind.css
COPY --from=tailwind-builder /app/app/static/js/diy-turbo.min.js ./app/static/js/diy-turbo.min.js

# Run tests during the build process
RUN pytest --maxfail=5 --disable-warnings -v || (echo "Tests failed. Exiting." && exit 1)

# Expose the port Flask will run on
EXPOSE 5000

# Set environment variables
ENV FLASK_ENV=production
ENV FLASK_CONFIG=ProductionConfig

# Command to run the Flask app
CMD ["gunicorn", "-b", "0.0.0.0:5000", "app:create_app()"]
