import fs from 'node:fs'
import crypto from 'node:crypto'
const sourcePath='contracts/external-data/kbx.external-data.json'
const text=fs.readFileSync(sourcePath,'utf8')
const source=JSON.parse(text)
const sha=crypto.createHash('sha256').update(text).digest('hex')
const ids=new Set()
for(const d of source.datasets??[]){if(ids.has(d.id))throw new Error(`duplicate external dataset ${d.id}`);ids.add(d.id)}
const manifest={schemaVersion:source.schemaVersion,contractVersion:source.contractVersion,sourceSha256:sha,principles:source.principles,datasets:source.datasets}
fs.mkdirSync('generated',{recursive:true});fs.writeFileSync('generated/external-data-manifest.json',JSON.stringify(manifest,null,2)+'\n')
const catalog=Object.fromEntries(source.datasets.map(x=>[x.id,x]))
fs.mkdirSync('packages/kbx-contracts/src/generated',{recursive:true})
fs.writeFileSync('packages/kbx-contracts/src/generated/externalDataCatalog.ts',`// generated from ${sourcePath}; do not edit.\nimport type { KbxExternalDataDatasetDefinition } from '../externalData'\nexport const kbxExternalDataSourceSha256='${sha}' as const\nexport const kbxExternalDataCatalog=${JSON.stringify(catalog,null,2)} as const satisfies Record<string,KbxExternalDataDatasetDefinition>\nexport type KbxExternalDataDatasetId=keyof typeof kbxExternalDataCatalog\n`)
const esc=s=>String(s).replaceAll('\\','\\\\').replaceAll('"','\\"')
fs.mkdirSync('backend/Shared/ExternalData/Generated',{recursive:true})
const rows=source.datasets.map(d=>`        ["${esc(d.id)}"] = new("${esc(d.id)}", "${esc(d.providerId)}", "${esc(d.providerOperationId)}", "${esc(d.canonicalType)}", "${esc(d.normalizer)}", "${esc(d.normalizerVersion)}", "${esc(d.freshness.mode)}", ${d.freshness.freshForSeconds??'null'}, ${d.freshness.maxStaleSeconds??'null'}, ${d.freshness.backgroundRefresh?'true':'false'}, "${esc(d.snapshot.rawRetention)}", ${d.snapshot.normalizedRetentionDays}, "${esc(d.ui.sourceLabel)}")`).join(',\n')
fs.writeFileSync('backend/Shared/ExternalData/Generated/KbxExternalDataCatalog.g.cs',`// generated from ${sourcePath}; do not edit.\nnamespace Kbx.Shared.ExternalData.Generated;\npublic sealed record KbxExternalDataDatasetDefinition(string Id,string ProviderId,string ProviderOperationId,string CanonicalType,string Normalizer,string NormalizerVersion,string FreshnessMode,int? FreshForSeconds,int? MaxStaleSeconds,bool BackgroundRefresh,string RawRetention,int NormalizedRetentionDays,string SourceLabel);\npublic static class KbxExternalDataCatalog { public const string SourceSha256="${sha}"; public static readonly IReadOnlyDictionary<string,KbxExternalDataDatasetDefinition> All=new Dictionary<string,KbxExternalDataDatasetDefinition>(StringComparer.Ordinal) {\n${rows}\n    }; }\n`)
console.log(`external-data contracts generated: ${source.datasets.length}, SHA ${sha.slice(0,12)}`)
