/**
 * Thin _gen/ wrapper for the scaffold-contracts generator.
 *
 * The actual generation logic lives in scripts/monorepo/generate-scaffold-contracts.js.
 * This wrapper provides the canonical generate() entry point so the generator
 * participates in the @repo/gen-utils pattern (snapshot tests, drift detection,
 * Turbo gen task).
 *
 * DO NOT move logic here — edit the script instead, then re-run generate().
 */

import { spawnSync } from 'node:child_process'
import { fileURLToPath } from 'node:url'
import { resolve, dirname } from 'node:path'

const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)

/** Monorepo root — four levels up from packages/core/src/_gen/ */
const ROOT = resolve(__dirname, '..', '..', '..', '..')

/**
 * Run the scaffold-contracts generator.
 * Delegates to scripts/monorepo/generate-scaffold-contracts.js via child process
 * so the existing script is the single source of implementation.
 */
export function generate(): void {
  const result = spawnSync('node', ['scripts/monorepo/generate-scaffold-contracts.js'], {
    stdio: 'inherit',
    cwd: ROOT
  })

  if (result.error) {
    throw new Error(`scaffold-contracts generator failed to spawn: ${result.error.message}`)
  }

  if (result.status !== 0) {
    throw new Error(`scaffold-contracts generator exited with status ${result.status}`)
  }
}

// Allow direct invocation: node packages/core/src/_gen/scaffold-contracts.ts
if (process.argv[1] && resolve(process.argv[1]) === __filename) {
  generate()
}
