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-property-area-verification.json'), 'utf8'))
const fail = (message) => { throw new Error(`Chrome PropertyArea check failed: ${message}`) }
if (report.schemaVersion !== 1 || report.status !== 'pass' || report.browserId !== 'chrome' || !/Chrome\//.test(report.userAgent || '') || report.crossOriginIsolated !== true) fail('browser boundary is invalid')
const requiredWorkerRequests = ['initialize', 'save-document', 'load-document', 'load-checkpoint', 'recovery-report', 'put-resource', 'get-resource', 'release-resource', 'dispose']
if (!report.worker?.constructed?.some(({ name }) => name === 'bitbybit-persistence') || !requiredWorkerRequests.every((type) => report.worker.requestTypes?.includes(type)) || report.worker.terminated?.includes('bitbybit-persistence') !== true) fail('persistence Worker lifecycle is incomplete')
if (report.ui?.areaReadOnly !== true || report.ui.beforeText !== '20 mm^2' || report.ui.afterText !== '0 mm^2' || report.ui.beforeArea !== 20 || report.ui.afterArea !== 0 || report.ui.beforeElementCount !== 2 || report.ui.afterElementCount !== 0 || report.ui.triggerLabel !== 'Clear subshape links' || report.ui.documentVersion !== 2 || report.ui.dirty !== true || report.ui.objectState !== 'touched' || report.ui.errors?.length !== 0) fail('production UI derived-area evidence is incomplete')
if (report.persistence?.mode !== 'sqlite-opfs' || report.persistence.sqliteWasm !== true || report.persistence.opfs !== true || report.persistence.savedMode !== 'sqlite-opfs' || report.persistence.loadedArea !== 0 || report.persistence.loadedAreaType !== 'App::PropertyArea' || report.persistence.loadedElementCount !== 0 || report.persistence.loadedElementsType !== 'App::PropertyLinkSubList' || report.persistence.checkpointVersion !== 2 || report.persistence.recoveryIntegrity !== 'ok' || report.persistence.fcstdAreaElement !== 'Float' || Number(report.persistence.fcstdAreaValue) !== 0 || report.persistence.fcstdElementsElement !== 'LinkSubList' || report.persistence.fcstdElementCount !== 0) fail('OPFS/FCStd persistence evidence is incomplete')
if (!(report.resource?.byteLength > 0) || report.resource.roundTrip !== true || report.resource.released !== true || report.resource.markerRemoved !== true || report.release?.shapeCount !== 0 || report.release.kernelReferenceCount !== 0 || report.release.workerTerminated !== true) fail('resource release evidence is incomplete')
console.log(JSON.stringify({ status: 'chrome-property-area-pass', ui: report.ui, persistence: report.persistence, workerRequests: report.worker.requestTypes, resource: report.resource, release: report.release }, null, 2))
