/**
 * cli:update-snapshot — execute.ts
 *
 * Re-scans `<moduleRoot>/pagespecs/` and writes the flat `key → hash` baseline
 * to `<moduleRoot>/.run-snapshot.json`. Reuses the SAME scanner as
 * `compute-page-diff` so the hashes written here are byte-identical to the
 * hashes that next run's diff compares against (no drift between writer/reader).
 */
import { writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { scanPagespecs, SNAPSHOT_FILENAME } from '../compute-page-diff/scan-pagespecs.js'
import type { UpdateSnapshotInput, UpdateSnapshotReport } from './types.js'

export function execute(input: UpdateSnapshotInput): UpdateSnapshotReport {
  const scan = scanPagespecs(input.moduleRoot)
  const pages: Record<string, string> = {}
  for (const { key, hash } of scan.pages) pages[key] = hash

  const lastRun = input.timestamp ?? new Date().toISOString()
  const snapshotPath = join(input.moduleRoot, SNAPSHOT_FILENAME)
  writeFileSync(snapshotPath, JSON.stringify({ lastRun, pages }, null, 2) + '\n', 'utf8')

  return { snapshotPath, pageCount: scan.pages.length, lastRun, warnings: scan.warnings }
}
