/**
 * Generate src/migrations/INDEX.md from REGISTRY metadata.
 *
 * Run via: pnpm build:migration-index
 *
 * Wired to the `prebuild` hook so `pnpm build` always regenerates.
 * INDEX.md is committed to the repo — a PR that adds a migration
 * without an INDEX.md update is a visible red flag for reviewers.
 */
import { writeFileSync } from 'node:fs'
import { resolve, dirname } from 'node:path'
import { fileURLToPath } from 'node:url'
import { REGISTRY } from '../src/migrations/registry.js'

const here = fileURLToPath(import.meta.url)
const repoRoot = resolve(dirname(here), '..')
const out = resolve(repoRoot, 'src/migrations/INDEX.md')

function escape(s: string): string {
  return s.replace(/\|/g, '\\|').replace(/\n/g, ' ')
}

const rows = REGISTRY.map(m =>
  `| \`${m.id}\` | ${m.appVersion} | ${m.introducedAt} | ${m.affects.join(', ')} | ${escape(m.summary)} |`,
)

const md = `<!-- Auto-generated by scripts/build-migration-index.ts. Do not edit by hand. -->
<!-- Regenerate with \`pnpm build:migration-index\`. -->

# Migration Index

Each row corresponds to one migration in \`src/migrations/\`. The runner applies pending migrations in this order on every boot, recording applied IDs in \`data/config/_meta.json\`. Migrations are idempotent in their body in addition to the journal-level guard.

| ID | App Version | Date | Affects | Summary |
|----|-------------|------|---------|---------|
${rows.join('\n')}
`

writeFileSync(out, md)
console.log(`Wrote ${out} (${REGISTRY.length} migrations)`)
