# ---------------------------------------------------------
# Stage 1: Build the React Frontend
# ---------------------------------------------------------
FROM node:18-alpine AS frontend-build

WORKDIR /app/frontend

# Copy package files first for better caching
COPY frontend/package*.json ./
RUN npm ci

# Copy source code and build
COPY frontend/ ./
RUN npm run build

# ---------------------------------------------------------
# Stage 2: Build the Python Backend & Assemble
# ---------------------------------------------------------
FROM python:3.11-slim

WORKDIR /app

# Install system dependencies (if needed for python packages)
# RUN apt-get update && apt-get install -y ... && rm -rf /var/lib/apt/lists/*

# Install Python dependencies
COPY backend/requirements ./requirements/
RUN pip install --no-cache-dir -r requirements/dev.txt

# Copy Flask application code
COPY backend/ ./

# Copy the built React files from Stage 1 into Flask's static folder
# Adjust 'build' to 'dist' if you are using Vite
COPY --from=frontend-build /app/frontend/dist ./app/static

# Create a non-root user for security
RUN useradd -m appuser
USER appuser

# Expose port
EXPOSE 8000

# Run with Gunicorn (Production WSGI Server)
# --bind 0.0.0.0 makes it accessible outside the container
# --access-logfile - sends access logs to stdout
# --error-logfile - sends error logs to stderr
# --capture-output ensures all output is captured
# --log-level info sets the logging level
CMD ["gunicorn", "--bind", "0.0.0.0:8000", "--workers", "2", "--access-logfile", "-", "--error-logfile", "-", "--capture-output", "--log-level", "info", "wsgi:app"]
