import fs from 'node:fs'

const livePath=process.env.KBX_LIVE_OPENAPI || 'artifacts/openapi.json'
if(!fs.existsSync(livePath)){
  console.log(`Live OpenAPI snapshot not found at ${livePath}; host DTO/schema gate is deferred until the .NET host is available.`)
  process.exit(0)
}
const contract=JSON.parse(fs.readFileSync('generated/api-manifest.json','utf8'))
const live=JSON.parse(fs.readFileSync(livePath,'utf8'))
const actual=new Map()
for(const [path,item] of Object.entries(live.paths??{})){
  for(const method of ['get','post','put','patch','delete']){
    const op=item?.[method];if(!op)continue
    if(op.operationId)actual.set(op.operationId,{method:method.toUpperCase(),path,op})
  }
}
const errors=[]
const normalize=p=>p.replace(/\{([^}:]+):[^}]+\}/g,'{$1}').toLowerCase()
for(const expected of contract.operations){
  const got=actual.get(expected.id)
  if(!got){errors.push(`live OpenAPI missing operationId ${expected.id}`);continue}
  if(got.method!==expected.method || normalize(got.path)!==normalize(expected.path))errors.push(`live route drift ${expected.id}: ${got.method} ${got.path}`)
  if((got.op['x-kbx-permission']??null)!==(expected.permission??null))errors.push(`live permission drift ${expected.id}`)
  if((got.op['x-kbx-idempotency']??'none')!==expected.idempotency)errors.push(`live idempotency drift ${expected.id}`)
  for(const status of ['400','403','404','409','422','500'])if(!got.op.responses?.[status])errors.push(`live Problem response ${status} missing: ${expected.id}`)
}
if(errors.length){console.error(errors.map(x=>`LIVE OPENAPI ERROR: ${x}`).join('\n'));process.exit(1)}
console.log(`Live OpenAPI contract PASS: ${contract.operationCount} operations with KBX metadata/problem responses.`)
