import { execFileSync } from 'node:child_process'
import { fileURLToPath } from 'node:url'
import path from 'node:path'

const root = path.resolve(process.argv[process.argv.indexOf('--root') + 1] ?? 'frontend')
const validators = [
  'validate-ui-boundary.mjs',
  'validate-kbx-component-manifest.mjs',
  'validate-kbx-screen-recipes.mjs',
  'validate-kbx-ai-components.mjs',
  'validate-kbx-exceptions.mjs',
]
const repositoryRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
const failures = []
for (const validator of validators) {
  const file = path.join(repositoryRoot, 'scripts', validator)
  try {
    const output = execFileSync(process.execPath, [file, '--root', root], { encoding: 'utf8' })
    process.stdout.write(`[PASS] ${validator}\n${output}`)
  } catch (error) {
    failures.push(validator)
    process.stdout.write(`[FAIL] ${validator}\n${error.stdout ?? ''}${error.stderr ?? ''}`)
  }
}
console.log(`KBX_GOVERNANCE validators=${validators.length} failures=${failures.length}`)
if (failures.length) console.log(`Failed validators: ${failures.join(', ')}`)
process.exitCode = failures.length ? 1 : 0
