# Stage 1: Build cf-api and common
FROM node:20-alpine AS js-builder

WORKDIR /build

# Copy JavaScript projects
COPY js/cf-api ./cf-api
COPY js/common ./common

# Build common package first
WORKDIR /build/common
RUN npm ci && npm run build

# Build cf-api
WORKDIR /build/cf-api
RUN npm ci

# Replace common package from registry with local build
RUN rm -rf node_modules/@codeflash-ai/common && \
    cp -r /build/common node_modules/@codeflash-ai/

# Clean and build cf-api
RUN rm -rf dist && npm run build

# Stage 2: Build aiservice
FROM python:3.12-slim AS python-builder

WORKDIR /build

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

# Install uv
RUN pip install uv

# Copy and build aiservice
COPY django/aiservice ./aiservice
WORKDIR /build/aiservice
RUN uv sync

# Stage 3: Final unified image
FROM node:20-alpine

# Install Python, PostgreSQL client, and supervisor
RUN apk add --no-cache \
    python3 \
    py3-pip \
    postgresql15 \
    postgresql15-client \
    supervisor \
    bash \
    && rm -rf /var/cache/apk/*

# Install Python dependencies globally
RUN pip3 install --break-system-packages uv

WORKDIR /app

# Copy cf-api from js-builder
COPY --from=js-builder /build/cf-api/dist ./cf-api/dist
COPY --from=js-builder /build/cf-api/package.json ./cf-api/package.json
COPY --from=js-builder /build/cf-api/package-lock.json ./cf-api/package-lock.json
COPY --from=js-builder /build/cf-api/node_modules ./cf-api/node_modules
COPY --from=js-builder /build/cf-api/resend ./cf-api/resend
COPY --from=js-builder /build/cf-api/github ./cf-api/github
COPY --from=js-builder /build/common ./common

# Copy node_modules into dist for ESM resolution
RUN cd cf-api && cp -rL node_modules dist/ 2>/dev/null || cp -r node_modules dist/

# Copy aiservice from python-builder
COPY --from=python-builder /build/aiservice ./aiservice

# Create PostgreSQL data directory
RUN mkdir -p /var/lib/postgresql/data /var/run/postgresql && \
    chown -R postgres:postgres /var/lib/postgresql /var/run/postgresql

# Copy configuration files
COPY deployment/onprem-simple/supervisord.conf /etc/supervisord.conf
COPY deployment/onprem-simple/init-db.sh /app/init-db.sh
COPY deployment/onprem-simple/startup.sh /app/startup.sh

RUN chmod +x /app/init-db.sh /app/startup.sh

# Expose ports
EXPOSE 5432 8000 3001

# Set environment variables
ENV PGDATA=/var/lib/postgresql/data
ENV PATH="/var/lib/postgresql/bin:${PATH}"

# Start supervisor
CMD ["/app/startup.sh"]