import fs from 'node:fs'

const components=JSON.parse(fs.readFileSync('generated/component-manifest.json','utf8'))
const catalog=JSON.parse(fs.readFileSync('generated/catalog-manifest.json','utf8'))
const catalogMap=new Map(catalog.map(x=>[x.component,x]))
const core=new Set([
  'KbxButton','KbxInput','KbxNumberField','KbxMoneyField','KbxQuantityField','KbxDateField','KbxDateRange','KbxSelect','KbxLookup',
  'KbxPageHeader','KbxCommandBar','KbxSearchPanel','KbxFormSection','KbxDataGrid','KbxBulkActionBar','KbxStatus',
  'KbxDialog','KbxDrawer','KbxToast','KbxConfirm','KbxExcelMenu','KbxExcelImport','KbxJobProgress',
  'KbxAuditTrail','KbxHelpPanel','KbxAiPanel','KbxProposalPanel','KbxListPage','KbxMasterPage','KbxTransactionPage','KbxMasterDetailPage','KbxQueuePage','KbxReconcilePage','KbxWmsMobilePage'
])
const groupName={primitive:'Primitive',business:'Business',template:'Template',wms:'WMS',shell:'Shell'}
const result={
  schemaVersion:'1.0',
  namingRule:'KBX/{Category}/{Component}',
  componentCount:components.length,
  coreComponentCount:core.size,
  components:components.map(c=>{
    const cat=catalogMap.get(c.name)
    return {
      codeName:c.name,
      figmaName:`KBX/${groupName[c.category] ?? c.category}/${c.name}`,
      category:c.category,
      version:c.version,
      designRequired:core.has(c.name),
      designStatus:cat?'cataloged':'code-only',
      variants:{state:cat?.states?.length?cat.states:['default'],density:['compact','comfortable',...(c.category==='wms'||c.name==='KbxWmsMobilePage'?['touch']:[])]}
    }
  })
}
fs.mkdirSync('design/figma',{recursive:true})
fs.writeFileSync('design/figma/components.contract.json',JSON.stringify(result,null,2)+'\n')
console.log(`generated Figma component contract for ${components.length} components (${core.size} core)`)
