#!/usr/bin/env node
/**
 * cli:update-snapshot — entry point.
 *
 * Writes `<moduleRoot>/.run-snapshot.json` from the current pagespecs. The
 * orchestrator calls this ONLY after a successful Phase 3a regeneration so the
 * baseline always reflects a known-good run.
 *
 * Invocation:
 *   npx --prefer-offline tsx skills/ba-develop/cli/update-snapshot/index.ts \
 *     --spec '{"moduleRoot":".smartstack/ba/<APP>/<MODULE>"}'
 */
import { parseArgs } from 'node:util'
import { validate } from './validate.js'
import { execute } from './execute.js'
import { generateEnvelope, failGenerate, printEnvelope } from '../../../lib/output.js'

const COMMAND = 'update-snapshot'

function main(): void {
  const { values } = parseArgs({
    options: { spec: { type: 'string' } },
    strict: true,
  })

  if (!values.spec) {
    printEnvelope(failGenerate(COMMAND, ['--spec is required']))
    process.exit(1)
  }

  let raw: unknown
  try {
    raw = JSON.parse(values.spec)
  } catch {
    printEnvelope(failGenerate(COMMAND, ['Invalid JSON in --spec']))
    process.exit(1)
  }

  const validation = validate(raw)
  if (!validation.valid || !validation.spec) {
    printEnvelope(failGenerate(COMMAND, validation.errors))
    process.exit(1)
  }

  const report = execute(validation.spec)

  printEnvelope(
    generateEnvelope(COMMAND, {
      data: { pageCount: report.pageCount, lastRun: report.lastRun },
      filesModified: [report.snapshotPath],
      warnings: report.warnings,
      nextSteps: [
        `Snapshot written with ${report.pageCount} page hash(es). Next \`compute-page-diff\` run will diff against this baseline.`,
      ],
    }),
  )

  process.exit(0)
}

main()
