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 runtimePath = '.cache/freecad/reference-desktop.json'
const sourcePaths = [
  '.cache/freecad/FreeCAD/src/App/PropertyFile.h',
  '.cache/freecad/FreeCAD/src/App/PropertyFile.cpp',
  '.cache/freecad/FreeCAD/src/Gui/propertyeditor/PropertyItem.h',
  '.cache/freecad/FreeCAD/src/Gui/propertyeditor/PropertyItem.cpp',
]
const outputPath = resolve(root, 'config/freecad-property-file-inventory.json')
const runtimeContent = await readFile(resolve(root, runtimePath))
const runtime = JSON.parse(runtimeContent)
const sourceContents = await Promise.all(sourcePaths.map((path) => readFile(resolve(root, path))))
const fail = (message) => { throw new Error(`FreeCAD PropertyFile inventory generation failed: ${message}`) }
if (runtime.schemaVersion !== 1 || runtime.freecadVersion !== '1.1.1' || runtime.gitCommit !== '0108fd4b4850cc46e625b60e53cea7a7bbe69f8d') fail('desktop oracle is not the locked FreeCAD baseline')
const records = []
for (const objectType of runtime.runtimeObjects?.types ?? []) {
  for (const property of objectType.properties ?? []) {
    if (property.typeId !== 'App::PropertyFile') 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: 'path-string',
        representation: 'App::PropertyString-derived UTF-8 path',
        defaultValue: property.default,
        writable: property.status.length === 0,
        externalResource: true,
        browserEditBoundary: 'host-absolute-paths are not written into the browser project; use an explicit project resource reference',
      },
      inputs: {
        accepted: ['string', '{filename:string,filter?:string}'],
        componentPaths: ['filename', 'filter'],
        emptyStringAccepted: true,
      },
      editor: 'Gui::PropertyEditor::PropertyFileItem',
      dependencies: [],
      applicability: { requiredObjectTypeId: objectType.typeId, source: 'Document.supportedTypes runtime inventory', propertyWriteRequiresShape: false },
    })
  }
}
records.sort((left, right) => `${left.objectTypeId}.${left.propertyName}`.localeCompare(`${right.objectTypeId}.${right.propertyName}`))
if (records.length !== 16) fail(`expected 16 native App::PropertyFile records, found ${records.length}`)
const report = {
  schemaVersion: 1,
  status: 'pass',
  baseline: { freecadVersion: runtime.freecadVersion, commit: runtime.gitCommit },
  propertyType: 'App::PropertyFile',
  recordCount: records.length,
  records,
  storage: { inheritedFrom: 'App::PropertyString', xmlElement: 'String', scalarEncoding: 'UTF-8 path string', externalResource: true, absoluteHostPathPolicy: 'preserve-or-reject; never rewrite into browser project' },
  provenance: {
    runtime: { path: runtimePath, bytes: runtimeContent.length, sha256: createHash('sha256').update(runtimeContent).digest('hex') },
    sources: sourcePaths.map((path, index) => ({ path, bytes: sourceContents[index].length, sha256: createHash('sha256').update(sourceContents[index]).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: 'freecad-property-file-inventory-generated', output: 'config/freecad-property-file-inventory.json', propertyType: report.propertyType, recordCount: report.recordCount }, null, 2))
