FROM node:20-alpine as builder

WORKDIR /app

# Add build arg to bust cache
ARG CACHEBUST=1

# Copy package files from frontend directory
COPY frontend/package.json ./

# Install dependencies
RUN npm install

# Copy the frontend application
COPY frontend/ ./

# Build the application with cache busting
RUN echo "Building with cache bust: $CACHEBUST" && npm run build

# Verify build output
RUN ls -la /app/dist || echo "Dist directory not created"
RUN ls -la /app/dist/assets || echo "Assets directory not created"

# Production stage with FastAPI
FROM python:3.11-alpine as production

WORKDIR /app

# Install system dependencies
RUN apk add --no-cache curl

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

# Copy built frontend assets from the builder stage
COPY --from=builder /app/dist /app/dist

# Copy FastAPI application
COPY backend/app /app/app
COPY backend/main.py ./

# Expose the port the app runs on
EXPOSE 8080

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

# Command to run the application
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8080"]

# Development stage with FastAPI
FROM python:3.11-alpine as development

WORKDIR /app

# Install system dependencies
RUN apk add --no-cache curl nodejs npm

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

# Copy built frontend assets from the builder stage
COPY --from=builder /app/dist /app/dist

# Verify the copied frontend build
RUN ls -la /app/dist || echo "Dist directory not created"
RUN ls -la /app/dist/assets || echo "Assets directory not created"

# Copy FastAPI application
COPY backend/app /app/app
COPY backend/main.py ./

# Expose the ports the app runs on (FastAPI and Vite dev server)
EXPOSE 8080 5173

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

# Command to run the application (FastAPI only in development)
# Frontend will be built and served by FastAPI
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8080", "--reload"]
