#!/bin/bash
set -euo pipefail

cd /app/labelapp

echo "==> Ensuring migration baseline..."
bun run scripts/ensure-migration-baseline.ts

echo "==> Running Drizzle migrations..."
bun run scripts/migrate.ts

echo "==> Checking if database needs seeding..."
ROW_COUNT=$(bun --eval "
import postgres from 'postgres';
const sql = postgres(process.env.DATABASE_URL);
const [{count}] = await sql\`SELECT count(*)::int as count FROM paragraphs\`;
console.log(count);
await sql.end();
" 2>/dev/null || echo "0")

if [ "$ROW_COUNT" = "0" ]; then
  export SEED_PARAGRAPHS_PATH=/app/data/paragraphs-clean.jsonl
  export SEED_ANNOTATIONS_PATH=/app/data/stage1.jsonl
  export SAMPLED_IDS_PATH=/app/labelapp/.sampled-ids.json

  echo "==> Database is empty, seeding..."
  bun run scripts/seed.ts

  echo "==> Running sampling..."
  bun run scripts/sample.ts

  echo "==> Running assignment generation..."
  bun run scripts/assign.ts

  echo "==> Seeding complete."
else
  echo "==> Database already seeded ($ROW_COUNT paragraphs). Skipping."
fi

echo "==> Starting Next.js server..."
exec bun run server.js
