#!/usr/bin/env node
/**
 * cli:scaffold-extension-config — Generate ExtensionConfig
 */
import { parseArgs } from 'node:util'
import { mkdirSync, writeFileSync } from 'node:fs'
import { dirname, resolve, join } from 'node:path'
import { validate } from './validate.js'
import { generate } from './generate.js'
import { generateEnvelope, failGenerate, printEnvelope } from '../../../../../lib/output.js'

const COMMAND = 'scaffold-extension-config'

function main(): void {
  const { values } = parseArgs({
    options: {
      spec: { type: 'string' },
      outdir: { 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']))
    process.exit(1)
  }

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

  const spec = raw as any
  const files = generate(spec)

  if (values.dry_run) {
    printEnvelope(generateEnvelope(COMMAND, {
      data: { dryRun: true, files: files.map(f => f.path) },
    }))
    process.exit(0)
  }

  const outdir = values.outdir ?? spec.projectPath
  const written: string[] = []

  for (const file of files) {
    const p = resolve(join(outdir, file.path))
    mkdirSync(dirname(p), { recursive: true })
    writeFileSync(p, file.content, 'utf-8')
    written.push(p)
  }

  printEnvelope(generateEnvelope(COMMAND, {
    data: { module: spec.module, fileCount: written.length },
    filesCreated: written,
    nextSteps: ['Import config in app entry point'],
  }))
}

main()
