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 report = JSON.parse(await readFile(resolve(root, 'config/freecad-property-integerset-mutation.json'), 'utf8'))
const fail = (message) => { throw new Error(`FreeCAD PropertyIntegerSet mutation check failed: ${message}`) }
if (report.schemaVersion !== 1 || report.status !== 'pass' || report.baselineId !== 'freecad-1.1.1-property-integerset-mutation' || report.freecadVersion !== '1.1.1' || report.gitCommit !== '0108fd4b4850cc46e625b60e53cea7a7bbe69f8d' || report.propertyType !== 'App::PropertyIntegerSet') fail('baseline is invalid')
if (report.caseCount !== 2 || report.cases?.length !== 2) fail('case inventory changed')
const expected = new Map([
  ['Fem::FemSetNodesObject', { property: 'Nodes', group: 'Node indexes', before: [1, 3], edited: [2, 5] }],
  ['Fem::FemSetElementNodesObject', { property: 'Elements', group: 'Element indexes', before: [4, 10], edited: [-1, 8] }],
])
for (const entry of report.cases) {
  const contract = expected.get(entry.objectTypeId)
  if (!contract || entry.propertyName !== contract.property || !isDeepStrictEqual(entry.before?.value, contract.before) || !isDeepStrictEqual(entry.touchedAfterEdit?.value, contract.edited) || !isDeepStrictEqual(entry.edited?.value, contract.edited) || !isDeepStrictEqual(entry.touchedAfterRestore?.value, contract.before) || !isDeepStrictEqual(entry.restored?.value, contract.before)) fail(`${entry.objectTypeId} values changed`)
  if (!entry.recompute?.initial || !entry.recompute.edit || !entry.recompute.restore || entry.neighborsPreserved !== true || entry.valueRestored !== true || entry.semanticStateRestored !== true || entry.objectsRestored !== true) fail(`${entry.objectTypeId} did not restore exactly`)
  for (const snapshot of [entry.before, entry.touchedAfterEdit, entry.edited, entry.touchedAfterRestore, entry.restored]) if (snapshot.propertyTypeId !== 'App::PropertyIntegerSet' || snapshot.group !== contract.group || !isDeepStrictEqual(snapshot.propertyStatus, []) || !isDeepStrictEqual(snapshot.editorMode, []) || snapshot.femMesh !== null || !snapshot.propertyNames?.includes(contract.property) || snapshot.shape?.applicable !== false || snapshot.objectSet?.length !== 1 || !Array.isArray(snapshot.objectState)) fail(`${entry.objectTypeId} metadata changed`)
  if (!isDeepStrictEqual(entry.touchedAfterEdit.objectState, ['Touched']) || !isDeepStrictEqual(entry.touchedAfterRestore.objectState, ['Touched'])) fail(`${entry.objectTypeId} touched trajectory changed`)
}
console.log(JSON.stringify({ status: 'freecad-property-integerset-mutation-pass', cases: report.cases.map(({ objectTypeId, before, edited, restored, semanticStateRestored }) => ({ objectTypeId, before: before.value, edited: edited.value, restored: restored.value, semanticStateRestored })) }, null, 2))

