import { createHash } from 'node:crypto'
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/chrome-partdesign-reference-lifecycle-verification.json'), 'utf8'))
const evidencePaths = [
  'public/chrome-partdesign-reference-lifecycle-harness.html',
  'src/facade/externalPartDesignLinks.ts',
  'src/facade/mockFacade.ts',
  'src/facade/geometryRuntime.ts',
  'src/facade/geometryWorker.ts',
  'node_modules/@bitbybit-dev/occt/bitbybit-dev-occt/bitbybit-dev-occt.a4a6ec2a.wasm',
]
const fail = (message) => { throw new Error(`Chrome PartDesign reference lifecycle: ${message}`) }
const same = (actual, expected) => JSON.stringify(actual) === JSON.stringify(expected)
const linked = (snapshot) => snapshot?.source?.status === 'open' && snapshot.properties?.XLink?.objectId === 'SourceBox' && snapshot.properties.XLinkSub?.subElements?.[0] === 'Face1' && snapshot.properties.XLinkList?.length === 2 && snapshot.properties.XLinkSubList?.length === 2 && snapshot.binder?.cacheState === 'linked' && snapshot.binder.support?.length === 1 && same(Object.values(snapshot.propertyStatus ?? {}), [['21'], ['21'], ['21'], ['21']])
const unresolved = (snapshot, status) => snapshot?.source?.status === status && snapshot.properties?.XLink === null && snapshot.properties.XLinkSub === null && snapshot.properties.XLinkList?.length === 0 && snapshot.properties.XLinkSubList?.length === 0 && snapshot.binder?.cacheState === 'cached' && snapshot.binder.support?.length === 0 && snapshot.binder.area === 30
const initialDimensions = (snapshot) => snapshot?.dimensions?.xLinkLength === 4 && snapshot.dimensions.xLinkSubWidth === 5 && same(snapshot.dimensions.xLinkListHeights, [6, 2]) && same(snapshot.dimensions.xLinkSubListAreas, [30, 14, 14]) && snapshot.binder?.area === 30
const editedDimensions = (snapshot) => snapshot?.dimensions?.xLinkLength === 8 && snapshot.dimensions.xLinkSubWidth === 9 && same(snapshot.dimensions.xLinkListHeights, [6, 4]) && same(snapshot.dimensions.xLinkSubListAreas, [54, 28, 28]) && snapshot.binder?.area === 54

if (report.schemaVersion !== 1 || report.browserId !== 'chrome' || report.status !== 'pass' || report.crossOriginIsolated !== true || !/HeadlessChrome\/150\./.test(report.userAgent ?? '')) fail('evidence is not passing, isolated, or from the locked Chrome baseline.')
if (!Array.isArray(report.evidenceInputs) || !same(report.evidenceInputs.map(({ path }) => path), evidencePaths)) fail('evidence input inventory is incomplete.')
for (const artifact of report.evidenceInputs) {
  const content = await readFile(resolve(root, artifact.path))
  const sha256 = createHash('sha256').update(content).digest('hex')
  if (artifact.bytes !== content.byteLength || artifact.sha256 !== sha256) fail(`stale implementation or artifact evidence for ${artifact.path}.`)
}
if (!linked(report.initial) || !initialDimensions(report.initial) || report.initial.history?.undo !== 0) fail('initial external reference graph is invalid.')
if (!unresolved(report.closed, 'closed') || !linked(report.relinkedAfterClose) || !initialDimensions(report.relinkedAfterClose)) fail('source close/relink behavior is invalid.')
if (!unresolved(report.missing, 'missing') || !unresolved(report.reopenedMissing, 'missing') || !linked(report.relinkedAfterMissing) || !initialDimensions(report.relinkedAfterMissing)) fail('OPFS missing-source reopen/relink behavior is invalid.')
if (!linked(report.edited) || !editedDimensions(report.edited) || report.edited.history?.undo !== 1 || !linked(report.undone) || !initialDimensions(report.undone) || report.undone.history?.redo !== 1 || !linked(report.redone) || !editedDimensions(report.redone)) fail('external source edit Undo/Redo behavior is invalid.')
if (!linked(report.reopened) || !editedDimensions(report.reopened) || !linked(report.reopenedUndo) || !initialDimensions(report.reopenedUndo) || !linked(report.reopenedRedo) || !editedDimensions(report.reopenedRedo)) fail('OPFS round-trip did not preserve external link history.')
if (report.released?.shapeCount !== 0 || report.released?.kernelReferenceCount !== 0 || report.released?.opfsRemoved !== true) fail('Chrome lifecycle leaked geometry or OPFS state.')

console.log(JSON.stringify({ status: 'chrome-partdesign-reference-lifecycle-pass', browserId: report.browserId, propertyKinds: ['XLink', 'XLinkSub', 'XLinkList', 'XLinkSubList'], sourceCloseRelink: true, missingSourceRoundtrip: true, editUndoRedo: true, opfsHistoryRoundtrip: true, released: { shapeCount: report.released.shapeCount, kernelReferenceCount: report.released.kernelReferenceCount } }, null, 2))
