import fs from 'node:fs'
const src=JSON.parse(fs.readFileSync('contracts/authorization/kbx.authorization.json','utf8'))
fs.mkdirSync('generated',{recursive:true})
fs.writeFileSync('generated/permission-manifest.json',JSON.stringify({schemaVersion:src.schemaVersion,permissionVersion:src.permissionVersion,permissions:src.permissions},null,2)+'\n')
fs.writeFileSync('generated/sensitive-data-manifest.json',JSON.stringify({schemaVersion:src.schemaVersion,policies:src.sensitiveDataPolicies,ai:src.ai},null,2)+'\n')
fs.mkdirSync('packages/kbx-contracts/src/generated',{recursive:true})
const ts=`// generated from contracts/authorization/kbx.authorization.json\nexport const kbxPermissionCatalog = ${JSON.stringify(src.permissions,null,2)} as const\nexport const kbxSensitiveDataPolicies = ${JSON.stringify(src.sensitiveDataPolicies,null,2)} as const\nexport const kbxAiAuthorizationPolicy = ${JSON.stringify(src.ai,null,2)} as const\nexport type KbxPermissionId = typeof kbxPermissionCatalog[number]['id']\n`
fs.writeFileSync('packages/kbx-contracts/src/generated/permissionCatalog.ts',ts)
fs.mkdirSync('backend/Shared/Authorization/Generated',{recursive:true})
const esc=s=>s.replace(/[^A-Za-z0-9]+/g,' ').trim().split(/\s+/).map(x=>x.charAt(0).toUpperCase()+x.slice(1)).join('')
const cs=['// <auto-generated />','namespace KBX.Shared.Authorization.Generated;','','public static class KbxPermissions','{',...src.permissions.map(p=>`    public const string ${esc(p.id)} = "${p.id}";`),'}','','public static class KbxSensitivePolicies','{',...src.sensitiveDataPolicies.map(p=>`    public const string ${esc(p.id)} = "${p.id}";`),'}',''].join('\n')
fs.writeFileSync('backend/Shared/Authorization/Generated/KbxPermissions.g.cs',cs)
console.log(`authorization contracts generated: permissions=${src.permissions.length}, sensitivePolicies=${src.sensitiveDataPolicies.length}`)
