import { createHash } from 'node:crypto'
import { isDeepStrictEqual } from 'node:util'
import { readFile } 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 reportPath = 'config/freecad-property-font-inventory.json'
const [runtimeContent, reportContent] = await Promise.all([readFile(resolve(root, runtimePath)), readFile(resolve(root, reportPath))])
const runtime = JSON.parse(runtimeContent)
const report = JSON.parse(reportContent)
const fail = (message) => { throw new Error(`FreeCAD PropertyFont inventory check failed: ${message}`) }
if (report.schemaVersion !== 1 || report.status !== 'pass' || report.propertyType !== 'App::PropertyFont' || report.classification !== 'opaque-fcstd-proxy' || report.baseline?.freecadVersion !== '1.1.1' || report.baseline?.commit !== '0108fd4b4850cc46e625b60e53cea7a7bbe69f8d') fail('report boundary is invalid')
if (report.recordCount !== 2 || report.objectTypeCount !== 2 || report.records?.length !== 2) fail('runtime record or host count changed')
if (report.storage?.inheritedFrom !== 'App::PropertyString' || report.storage.xmlElement !== 'String' || report.storage.scalarEncoding !== 'UTF-8 font family name' || report.storage.fontResourceEmbedded !== false || report.storage.browserBoundary !== 'preserve the family name; browser font availability is presentation-only') fail('storage boundary is invalid')
if (report.provenance?.runtime?.path !== runtimePath || report.provenance.runtime.bytes !== runtimeContent.length || report.provenance.runtime.sha256 !== createHash('sha256').update(runtimeContent).digest('hex')) fail('runtime provenance is stale')
for (const locked of report.provenance?.sources ?? []) {
  const content = await readFile(resolve(root, locked.path))
  if (content.length !== locked.bytes || createHash('sha256').update(content).digest('hex') !== locked.sha256) fail(`source provenance is stale for ${locked.path}`)
}

const nativeMatches = []
for (const objectType of runtime.runtimeObjects?.types ?? []) for (const property of objectType.properties ?? []) {
  if (property.typeId === 'App::PropertyFont') nativeMatches.push({ objectTypeId: objectType.typeId, objectAvailable: objectType.available === true, probeStatus: objectType.probeStatus, propertyName: property.name, group: property.group, status: property.status, defaultRaw: property.default })
}
const identity = ({ objectTypeId, objectAvailable, probeStatus, propertyName, group, status, defaultRaw }) => ({ objectTypeId, objectAvailable, probeStatus, propertyName, group, status, defaultRaw })
const sorted = (records) => records.map(identity).sort((left, right) => `${left.objectTypeId}.${left.propertyName}`.localeCompare(`${right.objectTypeId}.${right.propertyName}`))
if (!isDeepStrictEqual(sorted(nativeMatches), sorted(report.records))) fail('report diverges from the locked runtime oracle')
const expectedKeys = ['TechDraw::DrawViewAnnotation.Font', 'TechDraw::DrawViewSpreadsheet.Font']
if (!isDeepStrictEqual(report.records.map(({ objectTypeId, propertyName }) => `${objectTypeId}.${propertyName}`), expectedKeys)) fail('native host/property identities changed')
for (const record of report.records) {
  if (record.objectAvailable !== true || record.probeStatus !== 'available' || record.defaultRaw !== 'osifont' || !isDeepStrictEqual(record.status, []) || record.valueModel?.kind !== 'font-family-string' || record.valueModel.representation !== 'App::PropertyString-derived UTF-8 font family name' || record.valueModel.writable !== true || record.valueModel.installedFontRequired !== false || record.inputs?.accepted?.join('|') !== 'utf8-string' || record.inputs.emptyStringAccepted !== true || record.editor !== 'Gui::PropertyEditor::PropertyFontItem' || record.dependencies?.length !== 0 || record.applicability?.requiredObjectTypeId !== record.objectTypeId) fail(`native contract changed for ${record.objectTypeId}.${record.propertyName}`)
}
const sources = Object.fromEntries(await Promise.all(report.provenance.sources.map(async ({ path }) => [path, await readFile(resolve(root, path), 'utf8')])))
if (!sources['.cache/freecad/FreeCAD/src/App/PropertyStandard.h'].includes('class AppExport PropertyFont: public PropertyString') || !sources['.cache/freecad/FreeCAD/src/App/PropertyStandard.h'].includes('Gui::PropertyEditor::PropertyFontItem') || !sources['.cache/freecad/FreeCAD/src/App/PropertyStandard.cpp'].includes('TYPESYSTEM_SOURCE(App::PropertyFont, App::PropertyString)') || !sources['.cache/freecad/FreeCAD/src/Gui/propertyeditor/PropertyItem.cpp'].includes('QFontDatabase().families(QFontDatabase::Any)') || !sources['.cache/freecad/FreeCAD/src/Gui/propertyeditor/PropertyItem.cpp'].includes('auto cb = new QComboBox(parent)') || !sources['.cache/freecad/FreeCAD/src/Mod/TechDraw/App/DrawViewAnnotation.cpp'].includes('ADD_PROPERTY_TYPE(Font') || !sources['.cache/freecad/FreeCAD/src/Mod/TechDraw/App/DrawViewSpreadsheet.cpp'].includes('ADD_PROPERTY_TYPE(Font')) fail('locked PropertyFont class/editor/host contract changed')
console.log(JSON.stringify({ status: 'freecad-property-font-inventory-pass', propertyType: report.propertyType, recordCount: report.recordCount, objectTypes: report.records.map(({ objectTypeId }) => objectTypeId), defaultValue: 'osifont', classification: report.classification }, null, 2))
