# Build context: monorepo root (run: docker build -f labelapp/Dockerfile .)
FROM oven/bun:1.3.8 AS base

# -- Install dependencies --
FROM base AS deps
WORKDIR /app
COPY package.json ./
COPY packages/schemas/package.json packages/schemas/
COPY ts/package.json ts/
COPY labelapp/package.json labelapp/
# bun.lock intentionally excluded — bun hangs parsing the binary lockfile in Docker (bun bug)
RUN bun install

# -- Build Next.js --
FROM base AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY --from=deps /app/packages/schemas/node_modules ./packages/schemas/node_modules
COPY --from=deps /app/labelapp/node_modules ./labelapp/node_modules
COPY package.json ./
COPY packages/schemas/ packages/schemas/
COPY labelapp/ labelapp/
ENV NEXT_TELEMETRY_DISABLED=1
RUN cd labelapp && bun run build

# -- Production image --
FROM base AS runner
WORKDIR /app
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1

# Standalone server + static assets (includes postgres + drizzle-orm via serverExternalPackages)
COPY --from=builder /app/labelapp/.next/standalone ./
COPY --from=builder /app/labelapp/.next/static ./labelapp/.next/static
COPY --from=builder /app/labelapp/public ./labelapp/public

# Entrypoint scripts need drizzle-orm (migrator) + postgres beyond what standalone traces.
# Standalone copies the full package.json; swap it for a clean one so bun add works.
RUN cd labelapp && mv package.json package.json.bak && echo '{}' > package.json \
    && bun add postgres drizzle-orm \
    && mv package.json.bak package.json

# Drizzle migrations + schema (migrate.ts uses drizzle-orm programmatically — no drizzle-kit needed)
COPY --from=builder /app/labelapp/drizzle/ ./labelapp/drizzle/
COPY --from=builder /app/labelapp/db/ ./labelapp/db/

# Seed/sample/assign scripts + lib utilities
COPY --from=builder /app/labelapp/scripts/ ./labelapp/scripts/
COPY --from=builder /app/labelapp/lib/ ./labelapp/lib/

# Seed data (paragraphs + stage1 annotations + v2 holdout IDs)
COPY data/paragraphs/paragraphs-clean.jsonl /app/data/paragraphs-clean.jsonl
COPY data/annotations/stage1.jsonl /app/data/stage1.jsonl
COPY data/gold/v2-holdout-ids.json /app/data/v2-holdout-ids.json

# Entrypoint
COPY labelapp/entrypoint.sh /app/entrypoint.sh
RUN chmod +x /app/entrypoint.sh

EXPOSE 3000
ENV PORT=3000
ENV HOSTNAME=0.0.0.0

ENTRYPOINT ["/app/entrypoint.sh"]
