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

const root = path.resolve(process.argv[process.argv.indexOf('--root') + 1] ?? 'frontend')
const failures = []
const contractPath = path.join(root, 'src', 'shared', 'ui', 'screen-types', 'screen-recipes.json')
const sourcePath = path.join(root, 'src', 'shared', 'ui', 'screen-types', 'screenRecipe.ts')
if (!fs.existsSync(contractPath) || !fs.existsSync(sourcePath)) failures.push('recipe contract/source missing')
else {
  const contract = JSON.parse(fs.readFileSync(contractPath, 'utf8'))
  const source = fs.readFileSync(sourcePath, 'utf8')
  const ids = new Set()
  for (const recipe of contract.recipes ?? []) {
    if (ids.has(recipe.id)) failures.push(`duplicate recipe ${recipe.id}`)
    ids.add(recipe.id)
    for (const field of ['type', 'requiredPolicies', 'recoveryPolicies', 'securityPolicies']) {
      if (!recipe[field] || (Array.isArray(recipe[field]) && recipe[field].length === 0)) failures.push(`${recipe.id}: missing ${field}`)
    }
    const variable = recipe.id === 'T01' ? 'searchListRecipe' : recipe.id === 'T12' ? 'workQueueRecipe' : null
    if (!variable || !source.includes(`const ${variable}`)) failures.push(`${recipe.id}: source recipe is not represented`)
  }
  if (ids.size === 0) failures.push('no recipes registered')
}
console.log(`KBX_SCREEN_RECIPES failures=${failures.length}`)
for (const failure of failures) console.log(`FAIL ${failure}`)
process.exitCode = failures.length ? 1 : 0
