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

const root = resolve(new URL('..', import.meta.url).pathname)
const report = JSON.parse(await readFile(resolve(root, 'config/freecad-property-integerset-roundtrip.json'), 'utf8'))
const fail = (message) => { throw new Error(`FreeCAD PropertyIntegerSet roundtrip check failed: ${message}`) }
if (report.schemaVersion !== 1 || report.status !== 'pass' || report.baselineId !== 'freecad-1.1.1-property-integerset-roundtrip' || report.freecadVersion !== '1.1.1' || report.gitCommit !== '0108fd4b4850cc46e625b60e53cea7a7bbe69f8d') fail('baseline is invalid')
for (const [phase, snapshot, value] of [['nativeInitial', report.nativeInitial, [1, 3]], ['nativeReopened', report.nativeAfter?.reopened, [-1, 8]], ['nativeResaved', report.nativeAfter?.resaved, [-1, 8]]]) {
  if (!isDeepStrictEqual(snapshot?.objectSet, [{ name: 'NodesProbe', typeId: 'Fem::FemSetNodesObject' }]) || snapshot.object?.name !== 'NodesProbe' || snapshot.object.typeId !== 'Fem::FemSetNodesObject' || snapshot.object.propertyName !== 'Nodes' || snapshot.object.propertyTypeId !== 'App::PropertyIntegerSet' || snapshot.object.group !== 'Node indexes' || !isDeepStrictEqual(snapshot.object.value, value) || !isDeepStrictEqual(snapshot.object.propertyStatus, []) || snapshot.object.hasShapeProperty !== false) fail(`${phase} native semantics changed`)
}
if (report.web.before?.typeId !== 'App::PropertyIntegerSet' || report.web.before.element !== 'IntegerSet' || report.web.before.value !== '[1,3]' || report.web.after?.typeId !== 'App::PropertyIntegerSet' || report.web.after.element !== 'IntegerSet' || report.web.after.value !== '[-1,8]') fail('Web IntegerSet codec changed')
if (report.web.objectSetPreserved !== true || report.web.semanticObjectsPreserved !== true || report.web.opaqueEntriesPreserved !== true || !Number.isSafeInteger(report.web.opaquePathsPreserved)) fail('archive preservation changed')
if (report.classification?.webValue !== '[-1,8]' || !isDeepStrictEqual(report.classification.reopenedValue, [-1, 8]) || !isDeepStrictEqual(report.classification.resavedValue, [-1, 8]) || report.classification.nativeOutputMatches !== true || report.classification.unknownSemanticDrift !== false || report.classification.zeroUnknownDrift !== true) fail('roundtrip classification is incomplete')
for (const archive of Object.values(report.archives ?? {})) { const path = resolve(root, archive.path ?? ''); const content = await readFile(path); if ((await stat(path)).size !== archive.bytes || createHash('sha256').update(content).digest('hex') !== archive.sha256) fail(`archive is stale: ${archive.path}`) }
console.log(JSON.stringify({ status: 'freecad-property-integerset-roundtrip-pass', values: report.classification, opaquePathsPreserved: report.web.opaquePathsPreserved }, null, 2))
