# Build context: repo root (docker compose sets context: .)
# Multi-stage: Node.js build + Python sidecar + supervisord runtime

# ── Stage 1: Node.js build ───────────────────────────────────────
FROM node:22-slim AS ts-builder
RUN npm install -g pnpm@10
WORKDIR /app

# Copy workspace config + lockfile for dependency resolution
COPY package.json pnpm-workspace.yaml pnpm-lock.yaml tsconfig.base.json ./

# Copy all package.json files (pnpm needs these for workspace resolution)
COPY packages/errors/package.json packages/errors/
COPY packages/cosmos/package.json packages/cosmos/
COPY packages/blob/package.json packages/blob/
COPY packages/config/package.json packages/config/
COPY packages/auth/package.json packages/auth/
COPY packages/api-client/package.json packages/api-client/
COPY packages/fastify-core/package.json packages/fastify-core/
COPY packages/logger/package.json packages/logger/
COPY packages/monitoring/package.json packages/monitoring/
COPY packages/react-auth/package.json packages/react-auth/
COPY packages/design-tokens/package.json packages/design-tokens/
COPY packages/testing/package.json packages/testing/
COPY packages/extraction/package.json packages/extraction/
COPY services/extraction-service/package.json services/extraction-service/

# Install all workspace deps
RUN pnpm install --frozen-lockfile

# Copy source
COPY packages/ packages/
COPY services/extraction-service/tsconfig.json services/extraction-service/
COPY services/extraction-service/src/ services/extraction-service/src/

# Build packages first, then service
RUN pnpm -r --filter @lysnrai/extraction-service... build

# Deploy to isolated directory (production deps only)
RUN pnpm --filter @lysnrai/extraction-service deploy --legacy /app/deploy

# ── Stage 2: Production runtime (Node.js + Python sidecar) ───────
FROM node:22-slim

RUN apt-get update \
  && apt-get install -y --no-install-recommends python3 python3-venv supervisor \
  && rm -rf /var/lib/apt/lists/*

# Create an isolated venv for sidecar deps (avoids Debian PEP 668 restrictions).
RUN python3 -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"

WORKDIR /app

# Copy Node.js service
COPY --from=ts-builder /app/deploy ./

# Python sidecar (installed in the same OS/Python runtime to avoid ABI issues)
WORKDIR /app/python
COPY services/extraction-service/python/requirements.txt ./requirements.txt
RUN pip install --no-cache-dir -r requirements.txt
COPY services/extraction-service/python/src ./src

# Copy supervisord config
COPY services/extraction-service/supervisord.conf /etc/supervisor/conf.d/extraction.conf

ENV NODE_ENV=production
ENV PYTHON_SIDECAR_URL=http://localhost:4006

EXPOSE 4005
EXPOSE 4006

CMD ["supervisord", "-c", "/etc/supervisor/conf.d/extraction.conf"]
