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/PropertyStandard.h',
  '.cache/freecad/FreeCAD/src/App/PropertyStandard.cpp',
  '.cache/freecad/FreeCAD/src/Gui/propertyeditor/PropertyItem.h',
  '.cache/freecad/FreeCAD/src/Gui/propertyeditor/PropertyItem.cpp',
  '.cache/freecad/FreeCAD/src/Mod/TechDraw/App/DrawViewAnnotation.h',
  '.cache/freecad/FreeCAD/src/Mod/TechDraw/App/DrawViewAnnotation.cpp',
  '.cache/freecad/FreeCAD/src/Mod/TechDraw/App/DrawViewSpreadsheet.h',
  '.cache/freecad/FreeCAD/src/Mod/TechDraw/App/DrawViewSpreadsheet.cpp',
]
const outputPath = resolve(root, 'config/freecad-property-font-inventory.json')
const [runtimeContent, ...sourceContents] = await Promise.all([
  readFile(resolve(root, runtimePath)),
  ...sourcePaths.map((path) => readFile(resolve(root, path))),
])
const runtime = JSON.parse(runtimeContent)
const fail = (message) => { throw new Error(`FreeCAD PropertyFont 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::PropertyFont') 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: 'font-family-string',
        representation: 'App::PropertyString-derived UTF-8 font family name',
        writable: property.status.length === 0,
        installedFontRequired: false,
      },
      inputs: {
        accepted: ['utf8-string'],
        emptyStringAccepted: true,
        arbitraryFamilyNameAccepted: true,
      },
      editor: 'Gui::PropertyEditor::PropertyFontItem',
      editorModel: 'QFontDatabase family list exposed through QComboBox',
      dependencies: [],
      applicability: {
        requiredObjectTypeId: objectType.typeId,
        propertyWriteRequiresShape: false,
        source: 'Document.supportedTypes runtime inventory',
      },
    })
  }
}
records.sort((left, right) => `${left.objectTypeId}.${left.propertyName}`.localeCompare(`${right.objectTypeId}.${right.propertyName}`))
if (records.length !== 2 || new Set(records.map(({ objectTypeId }) => objectTypeId)).size !== 2) fail(`expected two native App::PropertyFont records, found ${records.length}`)
if (records.some(({ defaultRaw }) => defaultRaw !== 'osifont')) fail('locked default font changed')

const report = {
  schemaVersion: 1,
  status: 'pass',
  baseline: { freecadVersion: runtime.freecadVersion, commit: runtime.gitCommit },
  propertyType: 'App::PropertyFont',
  recordCount: records.length,
  objectTypeCount: new Set(records.map(({ objectTypeId }) => objectTypeId)).size,
  records,
  storage: {
    inheritedFrom: 'App::PropertyString',
    xmlElement: 'String',
    scalarEncoding: 'UTF-8 font family name',
    fontResourceEmbedded: false,
    browserBoundary: 'preserve the family name; browser font availability is presentation-only',
  },
  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-font-inventory-generated', output: 'config/freecad-property-font-inventory.json', propertyType: report.propertyType, recordCount: report.recordCount, objectTypeCount: report.objectTypeCount }, null, 2))
