import { copyFile, mkdir, readFile } from 'node:fs/promises'
import { resolve } from 'node:path'
import { pathToFileURL } from 'node:url'

const root = resolve(new URL('..', import.meta.url).pathname)
const dist = resolve(root, 'native/occt-history/dist')
const publicRoot = resolve(root, 'public/native/occt-history')
const artifacts = ['bitbybit-occt-history.js', 'bitbybit-occt-history.wasm', 'bitbybit-occt-history.data']
const factory = (await import(pathToFileURL(resolve(dist, artifacts[0])).href)).default
const module = await factory({ locateFile: (path) => resolve(dist, path) })
const callbacks = ['freecadNamingAbiVersion', 'freecadNamingCapabilitiesJson', 'freecadNamingEvidenceJson']
if (!callbacks.every((name) => typeof module[name] === 'function') || module.freecadNamingAbiVersion() !== 1) throw new Error('Refusing to publish an OCCT history artifact without the locked FreeCAD naming ABI.')
const descriptor = JSON.parse(module.freecadNamingCapabilitiesJson())
if (descriptor.freecadVersion !== '1.1.1' || descriptor.sourceCommit !== '0108fd4b4850cc46e625b60e53cea7a7bbe69f8d') throw new Error('Refusing to publish an unlocked FreeCAD naming ABI.')
await Promise.all(artifacts.map((name) => readFile(resolve(dist, name))))
await mkdir(publicRoot, { recursive: true })
await Promise.all(artifacts.map((name) => copyFile(resolve(dist, name), resolve(publicRoot, name))))
console.log(JSON.stringify({ status: 'occt-history-published', implementation: 'freecad-linked', artifacts, callbacks }, null, 2))
