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/occt-browser-verification.json'), 'utf8'))
if (report.schemaVersion !== 1 || report.status !== 'pass') throw new Error(`OCCT browser verification is not passing: ${report.status}`)
const browsers = report.browsers.filter((browser) => browser.status === 'pass')
if (browsers.length !== 1 || browsers[0]?.browserId !== 'chrome') throw new Error('Chrome evidence is required; other browsers are deferred.')
for (const browser of browsers) {
  const result = browser.report
  const opfsValid = result.opfs?.status === 'pass' && result.opfs.persistence === 'opfs'
  if (!result || result.crossOriginIsolated !== true || !opfsValid || result.initialize !== '8.0.0' || result.history?.provider !== 'occt-native' || result.abort !== 'recovered' || result.crashRecovery !== 'recovered') throw new Error(`Incomplete OPFS/Worker evidence for ${browser.browserId}.`)
  const requiredIterations = 1000
  const memory = result.memory
  const wasmValid = memory?.wasm?.peakHeapBytes <= memory?.budgets?.wasmPeakBytes && memory.wasm.retainedBytes <= memory.budgets.wasmRetainedBytes
  const browserMemoryValid = memory?.browser?.before?.bytes !== null && memory?.browser?.after?.bytes !== null && memory.browser.retainedBytes <= memory.budgets.browserRetainedBytes
  const gpuValid = memory?.gpu?.created === 0 && memory.gpu.released === 0 && memory.gpu.live === memory.budgets.gpuLiveResources
  const ownershipValid = memory?.ownership?.live === 0 && memory.ownership.created === memory.ownership.released
  if (memory?.iterations !== requiredIterations || memory.withinBudget !== true || !wasmValid || !browserMemoryValid || !gpuValid || !ownershipValid) throw new Error(`Memory ownership or budget gate failed for ${browser.browserId}.`)
}
console.log(JSON.stringify({
  status: 'occt-browser-verification-pass',
  browsers: browsers.map((browser) => browser.browserId),
  stressIterations: Object.fromEntries(browsers.map((browser) => [browser.browserId, browser.report.memory.iterations])),
  memoryWithinBudget: Object.fromEntries(browsers.map((browser) => [browser.browserId, browser.report.memory.withinBudget]))
}, null, 2))
