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

const root = path.resolve(process.argv[process.argv.indexOf('--root') + 1] ?? 'frontend')
const registryPath = path.join(root, 'src', 'shared', 'ui', 'kbx-exception-registry.json')
const failures = []
const today = new Date().toISOString().slice(0, 10)
if (!fs.existsSync(registryPath)) failures.push('missing exception registry')
else {
  const registry = JSON.parse(fs.readFileSync(registryPath, 'utf8'))
  const ids = new Set()
  for (const item of registry.exceptions ?? []) {
    if (ids.has(item.id)) failures.push(`duplicate exception ${item.id}`)
    ids.add(item.id)
    for (const field of ['id', 'screenId', 'type', 'reason', 'owner', 'introducedVersion', 'reviewAt', 'removalTarget', 'status']) {
      if (!item[field]) failures.push(`${item.id ?? 'unknown'}: missing ${field}`)
    }
    if (item.reviewAt && item.reviewAt < today && item.status === 'active') failures.push(`${item.id}: reviewAt expired`)
    if (!['active', 'removed', 'waived'].includes(item.status)) failures.push(`${item.id}: invalid status`)
  }
}
console.log(`KBX_EXCEPTIONS failures=${failures.length}`)
for (const failure of failures) console.log(`FAIL ${failure}`)
process.exitCode = failures.length ? 1 : 0
