import fs from 'node:fs'

const source=fs.readFileSync('packages/kbx-ui/src/catalog/componentCatalog.ts','utf8')
const commonInputStates=['default','required','readonly','disabled','error','keyboard']
const entries=[]
for(const line of source.split(/\r?\n/)){
  const component=line.match(/component:'([^']+)'/)?.[1]
  if(!component) continue
  const group=line.match(/group:'([^']+)'/)?.[1] ?? 'unknown'
  const inline=[...line.matchAll(/state:'([^']+)'/g)].map(x=>x[1])
  const states=line.includes('commonInputStates') ? commonInputStates : inline
  entries.push({component,group,scenarioProfile:line.includes('commonInputStates')?'common-input':undefined,states:[...new Set(states)]})
}
const duplicate=entries.filter((x,i,a)=>a.findIndex(y=>y.component===x.component)!==i)
if(duplicate.length){console.error(`duplicate catalog entries: ${duplicate.map(x=>x.component).join(', ')}`);process.exit(1)}
fs.mkdirSync('generated',{recursive:true})
fs.writeFileSync('generated/catalog-manifest.json',JSON.stringify(entries,null,2)+'\n')
console.log(`generated component catalog manifest with ${entries.length} entries`)
