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

# Build-time configurable: pass --build-arg REGISTRATION_ENABLED=false to disable registration
ARG REGISTRATION_ENABLED=true
ENV VITE_REGISTRATION_ENABLED=$REGISTRATION_ENABLED

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

# Build-time configurable for the backend: pass --build-arg REGISTRATION_ENABLED=false to disable registration
ARG REGISTRATION_ENABLED=true
ENV REGISTRATION_ENABLED=$REGISTRATION_ENABLED

# 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", "-", "--access-logformat", "%({x-forwarded-for}i)s - - [%(t)s] \"%(r)s\" %(s)s %(b)s \"%(f)s\" \"%(a)s\"", "--error-logfile", "-", "--capture-output", "--log-level", "info", "wsgi:app"]

ENV TZ=Africa/Nairobi
CMD ["gunicorn", "-c", "gunicorn.conf.py", "wsgi:app"]