import { createHash } from 'node:crypto'
import { readFile, writeFile } from 'node:fs/promises'
import { resolve } from 'node:path'

const root = resolve(new URL('..', import.meta.url).pathname)
const sourcePath = resolve(root, '.cache/freecad/reference-desktop.json')
const outputPath = resolve(root, 'config/freecad-property-integerset-inventory.json')
const sourceContent = await readFile(sourcePath)
const source = JSON.parse(sourceContent)
const fail = (message) => { throw new Error(`FreeCAD PropertyIntegerSet inventory generation failed: ${message}`) }
if (source.schemaVersion !== 1 || source.freecadVersion !== '1.1.1' || source.gitCommit !== '0108fd4b4850cc46e625b60e53cea7a7bbe69f8d') fail('desktop oracle is not the locked FreeCAD baseline')
const records = []
for (const objectType of source.runtimeObjects?.types ?? []) for (const property of objectType.properties ?? []) {
  if (property.typeId !== 'App::PropertyIntegerSet') continue
  records.push({
    objectTypeId: objectType.typeId,
    objectAvailable: objectType.available === true,
    probeStatus: objectType.probeStatus,
    propertyName: property.name,
    group: property.group,
    status: property.status,
    defaultRaw: property.default,
    valueModel: { kind: 'integer-set', writable: property.status.length === 0, elementType: 'signed-integer', cardinality: 'variable-unique-unordered', webRepresentation: 'sorted-safe-integer-array' },
    dependencies: [],
    applicability: { requiredObjectTypeId: objectType.typeId, source: 'Document.supportedTypes runtime inventory' },
  })
}
records.sort((left, right) => `${left.objectTypeId}.${left.propertyName}`.localeCompare(`${right.objectTypeId}.${right.propertyName}`))
if (records.length !== 2) fail(`expected two native App::PropertyIntegerSet records, found ${records.length}`)
const report = {
  schemaVersion: 1,
  status: 'pass',
  baseline: { freecadVersion: source.freecadVersion, commit: source.gitCommit },
  propertyType: 'App::PropertyIntegerSet',
  recordCount: records.length,
  writableRecordCount: records.filter(({ valueModel }) => valueModel.writable).length,
  records,
  source: { path: '.cache/freecad/reference-desktop.json', bytes: sourceContent.length, sha256: createHash('sha256').update(sourceContent).digest('hex') },
  classification: 'opaque-fcstd-proxy',
  nextPhases: ['B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'],
}
await writeFile(outputPath, `${JSON.stringify(report, null, 2)}\n`)
console.log(JSON.stringify({ status: report.status, output: 'config/freecad-property-integerset-inventory.json', propertyType: report.propertyType, recordCount: report.recordCount, writableRecordCount: report.writableRecordCount }, null, 2))

