# syntax=docker/dockerfile:1.4
# ==========================================
# STAGE 1: Base Setup
# ==========================================
FROM node:20-alpine AS base
ENV PNPM_HOME="/pnpm"
ENV PATH="$PNPM_HOME:$PATH"
# Enable pnpm natively in Node 20+
RUN corepack enable 

# ==========================================
# STAGE 2: Build the Monorepo
# ==========================================
FROM base AS builder
WORKDIR /monorepo

# 1. Copy the workspace configuration
COPY pnpm-workspace.yaml package.json ./

# 2. Copy the source code for all packages
COPY apps/ ./apps/
COPY packages/ ./packages/

# 3. Install all dependencies (including devDependencies required for Rollup & TSC)
# We use a cache mount to drastically speed up repeated Docker builds
RUN --mount=type=cache,id=pnpm,target=/pnpm/store pnpm install --frozen-lockfile

# 4. Build the entire workspace (Compiles UI -> Builds Registry -> Compiles MCP Server)
RUN pnpm run build:all

# 5. The Magic Step: Extract the mcp-server package and its production node_modules
# This creates a pristine, isolated app folder at /monorepo/pruned
RUN pnpm --filter @my-org/mcp-server deploy --prod /monorepo/pruned

# ==========================================
# STAGE 3: Final Production Image
# ==========================================
FROM base AS runner
WORKDIR /app

# Set production environment
ENV NODE_ENV="production"
EXPOSE 3000

# Copy ONLY the pruned, isolated server from the builder stage
COPY --from=builder /monorepo/pruned ./

# (Optional) Ensure registry.json is safely in the compiled dist directory
# If your build script outputs to /src, we move it to /dist where the runtime expects it
RUN cp ./src/registry.json ./dist/registry.json 2>/dev/null || true

# Start the server
CMD ["node", "dist/index.js"]