#!/usr/bin/env node
/**
 * cli:scaffold-doc — write the deterministic doc artifacts + emit a wiring plan.
 *
 * Writes (idempotently): the 4 i18n locale JSON files (FLAT) and the
 * docs-manifest.json entry. Computes a precise wiring plan (report.data.wiring)
 * for the in-place TSX edits (i18n config.ts, DocRoutes.tsx, DocPanelContext.tsx,
 * UserIndexPage.tsx) that Claude applies with Edit. Does NOT author the doc page
 * body or i18n content — those stay LLM-authored per templates.md.
 *
 * Usage:
 *   npx tsx skills/documentation/cli/scaffold-doc/index.ts --spec '<JSON>' [--dry_run]
 */
import { parseArgs } from 'node:util'
import { validate } from './validate.js'
import { generate } from './generate.js'
import { generateEnvelope, failGenerate, printEnvelope } from '../../../lib/output.js'

const COMMAND = 'scaffold-doc'

async function main(): Promise<void> {
  const { values } = parseArgs({
    options: { spec: { type: 'string' }, dry_run: { type: 'boolean', default: false } },
    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.value) {
    printEnvelope(failGenerate(COMMAND, validation.errors))
    process.exit(1)
  }
  const spec = validation.value
  if (values.dry_run) spec.dryRun = true
  try {
    const result = await generate(spec)
    printEnvelope(
      generateEnvelope(COMMAND, {
        data: { dryRun: spec.dryRun, namespace: spec.namespace, wiring: result.wiring },
        filesCreated: result.filesCreated,
        filesModified: result.filesModified,
        warnings: [...validation.warnings, ...result.warnings],
        nextSteps: result.nextSteps,
      }),
    )
  } catch (err) {
    printEnvelope(failGenerate(COMMAND, [err instanceof Error ? err.message : String(err)]))
    process.exit(1)
  }
}

void main()
