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-file-success.json'), 'utf8'))
const fail = (message) => { throw new Error(`FreeCAD PropertyFile success check failed: ${message}`) }
if (report.schemaVersion !== 1 || report.status !== 'pass' || report.baselineId !== 'freecad-1.1.1-property-file-success' || report.freecadVersion !== '1.1.1' || report.gitCommit !== '0108fd4b4850cc46e625b60e53cea7a7bbe69f8d' || report.propertyType !== 'App::PropertyFile') fail('baseline is invalid')
if (report.object?.typeId !== 'Mesh::Import' || report.property?.name !== 'FileName' || report.property?.typeId !== 'App::PropertyFile' || report.property?.group !== '') fail('native object/property identity changed')
if (report.asset?.exists !== true || report.asset.bytes <= 0 || !Array.isArray(report.asset.path) && typeof report.asset.path !== 'string') fail('valid mesh asset evidence is missing')
if (report.diagnostics?.exception !== null || report.diagnostics?.documentObjectCount !== 1 || !report.phases || !['default', 'valid-mesh', 'relative-path', 'restored'].every((id) => report.phases[id])) fail('native success phases are incomplete')
const objectSet = [{ name: 'FileProbe', typeId: 'Mesh::Import' }]
for (const [id, phase] of Object.entries(report.phases)) {
  if (phase.propertyTypeId !== 'App::PropertyFile' || !isDeepStrictEqual(phase.propertyStatus, []) || !isDeepStrictEqual(phase.editorMode, []) || !isDeepStrictEqual(phase.objectSet, objectSet) || typeof phase.recomputeResult !== 'boolean' || !Array.isArray(phase.objectState)) fail(`${id} native metadata is invalid`)
}
if (report.phases.default.value !== '' || report.phases.default.requested !== '' || report.phases['valid-mesh'].value !== report.asset.path || report.phases['valid-mesh'].requested !== report.asset.path || report.phases['relative-path'].value !== 'mesh-data/Cube.stl' || report.phases.restored.value !== report.asset.path) fail('PropertyFile values did not preserve native paths')
if (report.phases['valid-mesh'].statusString !== 'Valid' || !isDeepStrictEqual(report.phases['valid-mesh'].objectState, ['Up-to-date']) || report.phases['valid-mesh'].mesh?.applicable !== true || report.phases['valid-mesh'].mesh?.error) fail('valid path success evidence is incomplete')
if (report.phases.restored.statusString !== 'Valid' || !isDeepStrictEqual(report.phases.restored.objectState, ['Up-to-date']) || report.phases.restored.mesh?.error) fail('restored path state drifted')
console.log(JSON.stringify({ status: 'freecad-property-file-success-pass', propertyType: report.propertyType, phases: Object.keys(report.phases), validPath: report.phases['valid-mesh'].value, restored: report.phases.restored.value, hostMesh: report.phases['valid-mesh'].mesh }, null, 2))
