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 = resolve(root, '.cache/freecad/reference-desktop.json')
const sourcePaths = [
  '.cache/freecad/FreeCAD/src/App/PropertyStandard.h',
  '.cache/freecad/FreeCAD/src/App/PropertyStandard.cpp',
  '.cache/freecad/FreeCAD/src/Base/Color.h',
  '.cache/freecad/FreeCAD/src/Base/Color.cpp',
]
const outputPath = resolve(root, 'config/freecad-property-color-inventory.json')
const runtimeContent = await readFile(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 PropertyColor 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::PropertyColor') continue
    records.push({
      objectTypeId: objectType.typeId,
      objectAvailable: objectType.available === true,
      probeStatus: objectType.probeStatus,
      propertyName: property.name,
      group: property.group,
      status: property.status,
      defaultValue: property.default,
      valueModel: {
        kind: 'rgba-color',
        channels: ['red', 'green', 'blue', 'alpha'],
        canonicalRepresentation: 'four-channel-float-tuple',
        packedRepresentation: '0xRRGGBBAA',
        alphaSemantics: '1-opaque-0-transparent',
        writable: property.status.length === 0,
      },
      inputs: [
        { kind: 'float-tuple', cardinality: [3, 4], componentsMustHaveSameType: true, omittedAlpha: 1 },
        { kind: 'integer-tuple', cardinality: [3, 4], componentsMustHaveSameType: true, normalizationDivisor: 255, omittedAlpha: 1 },
        { kind: 'packed-integer', encoding: '0xRRGGBBAA' },
      ],
      dependencies: [],
      applicability: {
        requiredObjectTypeId: objectType.typeId,
        source: 'Document.supportedTypes runtime inventory',
        shapeRequired: false,
      },
    })
  }
}
records.sort((left, right) => `${left.objectTypeId}.${left.propertyName}`.localeCompare(`${right.objectTypeId}.${right.propertyName}`))
if (records.length !== 8) fail(`expected eight native App::PropertyColor records, found ${records.length}`)
const report = {
  schemaVersion: 1,
  status: 'pass',
  baseline: { freecadVersion: runtime.freecadVersion, commit: runtime.gitCommit },
  propertyType: 'App::PropertyColor',
  recordCount: records.length,
  records,
  storage: { xmlElement: 'PropertyColor', attribute: 'value', encoding: 'unsigned-decimal-packed-0xRRGGBBAA', legacyBeforeVersion: '1.1', legacyConversion: 'invert-alpha-byte' },
  provenance: {
    runtime: { path: '.cache/freecad/reference-desktop.json', 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-color-inventory-generated', output: 'config/freecad-property-color-inventory.json', propertyType: report.propertyType, recordCount: report.recordCount }, null, 2))
