import { readFile } from 'node:fs/promises'
import { resolve } from 'node:path'

const root = resolve(new URL('..', import.meta.url).pathname)
const reportNames = ['fem', 'cam', 'robot', 'inspection', 'data', 'addon', 'script']
const [coverage, inventory, pkg, reports] = await Promise.all([
  readFile(resolve(root, 'config/platform-module-coverage.json'), 'utf8').then(JSON.parse),
  readFile(resolve(root, 'config/freecad-source-inventory.json'), 'utf8').then(JSON.parse),
  readFile(resolve(root, 'package.json'), 'utf8').then(JSON.parse),
  Promise.all(reportNames.map((name) => readFile(resolve(root, `config/chrome-${name}-verification.json`), 'utf8').then(JSON.parse))),
])
if (coverage.schemaVersion !== 1 || coverage.baseline?.commit !== inventory.baseline?.commit) throw new Error('Platform coverage baseline does not match the locked FreeCAD inventory.')
if (!Array.isArray(coverage.modules) || coverage.modules.length !== 34 || inventory.modules.length !== 34) throw new Error('Platform closure must enumerate exactly 34 modules.')
const expected = inventory.modules.map((module) => module.name).sort()
const actual = coverage.modules.map((module) => module.name).sort()
if (JSON.stringify(actual) !== JSON.stringify(expected) || new Set(actual).size !== 34) throw new Error('Platform coverage names do not match the 34-module source inventory.')
const levels = new Set(['exact', 'compatible', 'proxy', 'development'])
for (const module of coverage.modules) {
  if (!levels.has(module.level) || !module.boundary?.trim() || !pkg.scripts?.[module.evidence]) throw new Error(`Platform module ${module.name} has an invalid level, boundary or executable evidence.`)
  if (['scope-only', 'unsupported'].includes(module.level)) throw new Error(`Platform module ${module.name} remains unexplained: ${module.level}`)
}
for (const [index, report] of reports.entries()) {
  const name = reportNames[index]
  if (report.schemaVersion !== 1 || report.status !== 'pass' || report.browserId !== 'chrome' || report.crossOriginIsolated !== true || !/Chrome/i.test(report.browser?.product || '')) throw new Error(`Platform ${name} browser evidence is not passing.`)
  if (report.persistence?.mode !== 'sqlite-opfs' || report.persistence.byteLength <= 0 || report.persistence.roundTrip !== true || report.persistence.released !== true) throw new Error(`Platform ${name} persistence evidence is incomplete.`)
  if (report.opfs?.markerRemoved !== true || report.afterRelease?.shapeCount !== 0 || report.afterRelease.kernelReferenceCount !== 0) throw new Error(`Platform ${name} lifecycle evidence is incomplete.`)
}
const [fem, cam, robot, inspection, data, addon, script] = reports
if (fem.solve?.strategy !== 'local-reference' || fem.solve.nodeSets !== 1 || JSON.stringify(fem.solve.resultFields) !== JSON.stringify(['displacement', 'stress'])) throw new Error('Platform FEM solve evidence is incomplete.')
if (cam.job?.collisionFixture < 1 || cam.job.unsafePostRejected !== true || cam.job.deterministic !== true) throw new Error('Platform CAM collision/post evidence is incomplete.')
if (robot.trajectory?.poses !== 5 || robot.trajectory.maxReach !== 6 || robot.trajectory.collisions < 1 || robot.trajectory.controllerBytes <= 0) throw new Error('Platform Robot kinematics evidence is incomplete.')
if (inspection.measurements?.deviationStatus !== 'resolved' || inspection.measurements.topoRefs !== 2 || Math.abs(inspection.measurements.sectionArea - 24) > 1e-5) throw new Error('Platform Inspection evidence is incomplete.')
if (data.adapters?.total !== 7 || data.records?.total !== 7 || data.adapters.supported !== 4 || data.adapters.proxy !== 3 || data.points?.sourceCount !== 6 || data.points?.polygonCroppedCount !== 4 || data.reverseEngineering?.cylinderRadius !== 3 || data.reverseEngineering?.polynomialRms > 1e-7 || data.reverseEngineering?.segmentCount !== 2) throw new Error('Platform specialist data adapter evidence is incomplete.')
if (!addon.security?.forgedRejected || !addon.security.permissionRejected || !addon.security.removed || addon.catalog?.rollbackVersion !== '1.0.0') throw new Error('Platform addon governance evidence is incomplete.')
if (!script.security?.noDynamicExecution || JSON.stringify(script.security.deniedCapabilities) !== JSON.stringify(['file', 'network', 'time', 'resource'])) throw new Error('Platform script sandbox evidence is incomplete.')
const summary = Object.fromEntries([...levels].map((level) => [level, coverage.modules.filter((module) => module.level === level).length]))
console.log(JSON.stringify({ status: 'platform-closure-pass', modules: coverage.modules.length, unexplained: 0, summary, evidenceScripts: new Set(coverage.modules.map((module) => module.evidence)).size, browserSuites: reportNames.length }, null, 2))
