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

const root = resolve(new URL('..', import.meta.url).pathname)
const lockfileSha256 = createHash('sha256').update(await readFile(resolve(root, 'package-lock.json'))).digest('hex')
const report = JSON.parse(await readFile(resolve(root, 'config/npm-audit-critical.json'), 'utf8'))
if (report.schemaVersion !== 1 || report.status !== 'pass' || report.command !== 'npm audit --omit=dev --audit-level=critical --json') throw new Error('npm critical audit report is not passing.')
if (report.lockfileSha256 !== lockfileSha256) throw new Error('npm critical audit report does not match package-lock.json; rerun `npm run test:dependency-audit`.')
if (Number(report.metadata?.vulnerabilities?.critical ?? -1) !== 0 || Object.keys(report.vulnerabilities ?? {}).length !== 0) throw new Error('npm critical audit contains unresolved vulnerabilities.')
console.log(JSON.stringify({ status: 'dependency-audit-pass', critical: report.metadata.vulnerabilities.critical, productionDependencies: report.metadata.dependencies.prod, totalDependencies: report.metadata.dependencies.total, lockfileSha256 }, null, 2))
