import fs from 'node:fs'
import path from 'node:path'

const root = path.resolve(process.argv[process.argv.indexOf('--root') + 1] ?? 'frontend')
const manifestPath = path.join(root, 'src', 'shared', 'ui', 'component-manifest.json')
const failures = []
const allowedTiers = new Set(['L0', 'L1', 'L2', 'L3', 'L4'])
if (!fs.existsSync(manifestPath)) failures.push('missing component manifest')
else {
  const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'))
  if (manifest.schemaVersion !== '1.0') failures.push('unsupported manifest schema')
  if (!Array.isArray(manifest.components) || manifest.components.length < 6) failures.push('golden component coverage is incomplete')
  const ids = new Set()
  const names = new Set()
  for (const item of manifest.components ?? []) {
    if (ids.has(item.id)) failures.push(`duplicate component id ${item.id}`)
    if (names.has(item.name)) failures.push(`duplicate component name ${item.name}`)
    ids.add(item.id); names.add(item.name)
    if (!allowedTiers.has(item.tier)) failures.push(`${item.name}: invalid tier`)
    if (!item.owner || !item.vendorPolicy || !item.requiredContracts?.length) failures.push(`${item.name}: incomplete governance fields`)
    const source = path.join(root, 'src', 'shared', 'ui', 'components', path.basename(item.source))
    if (!fs.existsSync(source)) failures.push(`${item.name}: missing source ${item.source}`)
    if (item.name === 'KsDataGrid' && item.vendorPolicy !== 'strong-facade-no-raw-api') failures.push('KsDataGrid must be a strong facade')
  }
}
console.log(`KBX_COMPONENT_MANIFEST failures=${failures.length}`)
for (const failure of failures) console.log(`FAIL ${failure}`)
process.exitCode = failures.length ? 1 : 0
