# ============================================
# Stage 1: Build React Frontend
# ============================================
FROM node:20-alpine AS frontend-build

WORKDIR /build/frontend

# Nuke NODE_ENV — CapRover/Docker can inject production
# which prevents devDependencies (vite, tailwind) from installing
ENV NODE_ENV=

COPY frontend/package.json frontend/package-lock.json* ./

# Force ALL deps including dev
RUN npm install --legacy-peer-deps --include=dev && \
  echo "=== vite check ===" && \
  npx vite --version

COPY frontend/ ./

RUN NODE_ENV=production npx vite build && \
  echo "=== dist ===" && \
  ls -la dist/

# ============================================
# Stage 2: Python Backend + Serve Frontend
# ============================================
FROM python:3.11-slim

RUN apt-get update && apt-get install -y --no-install-recommends \
  build-essential \
  ffmpeg \
  && rm -rf /var/lib/apt/lists/*

WORKDIR /app

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY backend/ ./backend/

COPY --from=frontend-build /build/frontend/dist ./frontend/dist

RUN echo "=== Frontend ===" && ls -la frontend/dist/ && \
  echo "=== Assets ===" && ls -la frontend/dist/assets/ || true

COPY warmup.py /tmp/warmup.py
RUN python /tmp/warmup.py && rm /tmp/warmup.py

RUN mkdir -p /data/chromadb /data/uploads /data/uploads/chat_attachments

ENV PYTHONUNBUFFERED=1

EXPOSE 80

CMD ["python", "-m", "uvicorn", "backend.main:app", "--host", "0.0.0.0", "--port", "80", "--workers", "1"]