import { createHash } from 'node:crypto'
import { access, readFile } from 'node:fs/promises'
import { resolve } from 'node:path'

const root = resolve(new URL('..', import.meta.url).pathname)
const artifactNames = ['bitbybit-occt-history.js', 'bitbybit-occt-history.wasm']
const distRoot = resolve(root, 'native/occt-history/dist')
const publicRoot = resolve(root, 'public/native/occt-history')
const exists = async (path) => access(path).then(() => true).catch(() => false)
const hash = (bytes) => createHash('sha256').update(bytes).digest('hex')
const distPresent = await Promise.all(artifactNames.map((name) => exists(resolve(distRoot, name))))
const publicPresent = await Promise.all(artifactNames.map((name) => exists(resolve(publicRoot, name))))
if (!distPresent.some(Boolean) && !publicPresent.some(Boolean)) {
  console.log(JSON.stringify({ status: 'artifact-not-built', reason: 'Run ./npmw run build:occt-history when the pinned Emscripten/OCCT inputs are available.' }, null, 2))
  process.exit(0)
}
if (distPresent.some((present) => !present) || publicPresent.some((present) => !present)) throw new Error('OCCT history browser artifact is incomplete; JS and WASM must be published together.')
for (const name of artifactNames) {
  const distBytes = await readFile(resolve(distRoot, name))
  const publicBytes = await readFile(resolve(publicRoot, name))
  if (hash(distBytes) !== hash(publicBytes)) throw new Error(`OCCT history ${name} differs between dist and public deployment paths.`)
  if (distBytes.length === 0) throw new Error(`OCCT history ${name} is empty.`)
}
const javascript = await readFile(resolve(publicRoot, 'bitbybit-occt-history.js'), 'utf8')
if (!javascript.includes('bitbybit-occt-history.wasm') || !javascript.includes('export default')) throw new Error('OCCT history JS artifact does not expose the expected ESM factory and WASM locator.')
const workerClient = await readFile(resolve(root, 'src/facade/nativeHistoryWorkerClient.ts'), 'utf8')
if (!workerClient.includes("'/native/occt-history/bitbybit-occt-history.js'")) throw new Error('Native history Worker client URL does not match the published artifact.')
const files = []
for (const name of artifactNames) files.push({ name, sha256: hash(await readFile(resolve(publicRoot, name))) })
console.log(JSON.stringify({ status: 'artifact-pass', files }, null, 2))
