// Halflight watch contract-mirror config plugin.
//
// The watch target has no JS runtime, so a handful of constants that are
// canonical on the JS/TS side (branding strings, the tapestry letter
// alphabet, the page-window math) need to be mirrored as Swift. This
// plugin runs the targets/_scripts/gen-*.mjs scripts at config-resolution
// time, writing Swift files into targets/watch/Generated/. The directory
// is .gitignored — it's pure build output.
//
// Order matters in app.config.ts: this plugin must come BEFORE
// '@bacons/apple-targets' so the Generated/ Swift files exist when the
// apple-targets plugin globs the watch target's *.swift sources.
//
// Re-runs on every prebuild. The generators are <10ms total and
// idempotent, so the cost is invisible.

const { spawnSync } = require('node:child_process')
const { existsSync } = require('node:fs')
const path = require('node:path')

function withWatchGenerated(config) {
  const projectRoot = config._internal?.projectRoot ?? process.cwd()
  const script = path.join(projectRoot, 'targets', '_scripts', 'gen-all.mjs')
  if (!existsSync(script)) {
    throw new Error(
      `withWatchGenerated: generator script not found at ${script}. ` +
        'Did the targets/_scripts/ directory get deleted?'
    )
  }
  const result = spawnSync(process.execPath, [script], {
    cwd: projectRoot,
    encoding: 'utf8',
  })
  if (result.status !== 0) {
    const stderr = result.stderr || result.stdout || '(no output)'
    throw new Error(
      `withWatchGenerated: gen-all.mjs failed (exit ${result.status}):\n${stderr}`
    )
  }
  if (process.env.HALFLIGHT_VERBOSE_PLUGINS) {
    console.log(result.stdout)
  }
  return config
}

module.exports = withWatchGenerated
