import { createHash } from 'node:crypto'
import { readFile, stat, writeFile } from 'node:fs/promises'
import { resolve } from 'node:path'
import { pathToFileURL } from 'node:url'
import { runFreeCadNamingProductionMatrix } from './freecad-naming-production-matrix.mjs'

const root = resolve(new URL('..', import.meta.url).pathname)
const dist = resolve(root, 'native/occt-history/dist')
const matrixPath = resolve(root, 'scripts/freecad-naming-production-matrix.mjs')
const artifactNames = ['bitbybit-occt-history.js', 'bitbybit-occt-history.wasm', 'bitbybit-occt-history.data']
const createModule = (await import(pathToFileURL(resolve(dist, artifactNames[0])).href)).default
const module = await createModule({ locateFile: (path) => resolve(dist, path) })
const report = await runFreeCadNamingProductionMatrix(module)
const artifacts = await Promise.all(artifactNames.map(async (name) => {
  const path = resolve(dist, name)
  const [bytes, content] = await Promise.all([stat(path).then(({ size }) => size), readFile(path)])
  return { name, bytes, sha256: createHash('sha256').update(content).digest('hex') }
}))
const matrixContent = await readFile(matrixPath)
const harness = { path: 'scripts/freecad-naming-production-matrix.mjs', bytes: matrixContent.length, sha256: createHash('sha256').update(matrixContent).digest('hex') }
const output = { ...report, runtime: 'node', artifacts, harness, generatedAt: new Date().toISOString() }
await writeFile(resolve(root, 'config/freecad-naming-production-verification.json'), `${JSON.stringify(output, null, 2)}\n`)
console.log(JSON.stringify(output, null, 2))
