import { execFile } from 'node:child_process'
import { createHash } from 'node:crypto'
import { readFile } from 'node:fs/promises'
import { resolve } from 'node:path'
import { promisify } from 'node:util'

const root = resolve(new URL('..', import.meta.url).pathname)
const report = JSON.parse(await readFile(resolve(root, 'config/chrome-cam-linuxcnc-machine-verification.json'), 'utf8'))
const manifest = JSON.parse(await readFile(resolve(root, 'config/linuxcnc-wasm-machine-artifact.json'), 'utf8'))
const offlineResources = JSON.parse(await readFile(resolve(root, 'config/offline-resources.json'), 'utf8'))
const lockedWorktree = offlineResources.archives.find((entry) => entry.id === 'linuxcnc-worktree')
const artifactRoles = (manifest.artifacts || []).map((artifact) => artifact.role)
if (manifest.schemaVersion !== 1 || manifest.worktreeRevision !== lockedWorktree?.revision || manifest.chromeVersion !== offlineResources.hostTools?.chrome || JSON.stringify(artifactRoles) !== JSON.stringify(['entry-html', 'case-registry', 'machine-config', 'application', 'controller-worker', 'wasm-loader', 'wasm-core'])) throw new Error('LinuxCNC WASM runtime manifest does not match the offline resource locks.')
if (manifest.artifacts.some(({ runtimeLoaded }) => typeof runtimeLoaded !== 'boolean') || manifest.artifacts.find(({ role }) => role === 'wasm-loader')?.runtimeLoaded !== false || manifest.artifacts.filter(({ role }) => role !== 'wasm-loader').some(({ runtimeLoaded }) => !runtimeLoaded)) throw new Error('LinuxCNC runtime-loaded artifact boundary is invalid.')
if (manifest.machineConfigPath !== manifest.artifacts.find(({ role }) => role === 'machine-config')?.path) throw new Error('LinuxCNC machine configuration is not pinned as a runtime artifact.')
const actualRevision = (await promisify(execFile)('git', ['-C', resolve(root, 'cnc_wams_gpt6/linuxcnc-master'), 'rev-parse', 'HEAD'])).stdout.trim()
if (actualRevision !== manifest.worktreeRevision) throw new Error('LinuxCNC worktree does not match the pinned revision.')
for (const artifact of manifest.artifacts || []) {
  const bytes = await readFile(resolve(root, manifest.distRoot, artifact.path))
  const sha256 = createHash('sha256').update(bytes).digest('hex')
  if (bytes.byteLength !== artifact.bytes || sha256 !== artifact.sha256) throw new Error(`LinuxCNC WASM artifact does not match its pinned identity: ${artifact.path}.`)
}
if (report.schemaVersion !== 1 || report.status !== 'pass' || report.browserId !== 'chrome') throw new Error('Chrome CAM LinuxCNC machine verification is not passing.')
if (JSON.stringify(report.stages) !== JSON.stringify(['CAD', 'OCL', 'CAMotics', 'GCODE', 'LinuxCNC WASM'])) throw new Error('CAM machine stage order is invalid.')
if (report.openCamLib?.backend !== 'upstream-opencamlib-wasm' || report.openCamLib.sourceRevision?.length !== 40 || report.openCamLib.artifactSha256?.length !== 64 || report.openCamLib.triangleCount < 2 || report.openCamLib.inputPoints < 2 || report.openCamLib.outputPoints < report.openCamLib.inputPoints || !(report.openCamLib.sampling > 0)) throw new Error('OpenCAMLib WASM stage evidence is incomplete.')
if (!report.gcode?.hasM428 || !report.gcode.hasM429 || !report.gcode.hasG93 || !report.gcode.hasG94 || !report.gcode.hasB || !report.gcode.hasC359 || !report.gcode.hasC361) throw new Error('LinuxCNC XYZBC RTCP G-code evidence is incomplete.')
if (report.machine?.backend !== 'linuxcnc-wasm' || report.machine.status !== 'accepted' || report.machine.dryRunStatus !== 'dry-run' || report.machine.parserAuthority !== 'linuxcnc-wasm' || report.machine.machineCase !== manifest.machineCase || report.machine.dryRunMachineCase !== manifest.machineCase || report.machine.lines < 10 || report.machine.lines >= 1000 || report.machine.blocks < 2 || report.machine.blocks >= 1000 || report.machine.trajectorySegments < 2 || report.machine.trajectorySegments >= 1000) throw new Error('LinuxCNC WASM machine acceptance evidence is incomplete or belongs to a different program or machine case.')
if (report.runtime?.server !== 'managed-vite-preview' || report.runtime.worktreeRevision !== manifest.worktreeRevision || report.runtime.machineCase !== report.machine.machineCase) throw new Error('LinuxCNC WASM managed runtime identity is incomplete.')
const chromeMajor = manifest.chromeVersion.split('.')[0]
if (report.browser?.product !== manifest.chromeVersion || !String(report.browser?.userAgent || '').includes(`Chrome/${chromeMajor}.`)) throw new Error('Chrome runtime is not the pinned version.')
if (JSON.stringify(report.runtime.artifacts) !== JSON.stringify(manifest.artifacts)) throw new Error('LinuxCNC WASM artifact hashes do not match the pinned manifest.')
if (JSON.stringify(report.runtime.loadedArtifacts) !== JSON.stringify(manifest.artifacts.filter(({ runtimeLoaded }) => runtimeLoaded).map(({ role, path }) => ({ role, path, status: 200 })))) throw new Error('Chrome did not load every pinned LinuxCNC runtime artifact.')
console.log(JSON.stringify({ status: 'chrome-cam-linuxcnc-machine-pass', stages: report.stages, openCamLib: report.openCamLib, gcode: report.gcode, machine: report.machine, browser: report.browser }, null, 2))
