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

const root = resolve(new URL('..', import.meta.url).pathname)
const inventory = JSON.parse(await readFile(resolve(root, 'config/freecad-entrypoint-inventory.json'), 'utf8'))
const fail = (message) => { throw new Error(`FreeCAD entrypoint inventory: ${message}`) }
if (inventory.schemaVersion !== 1 || inventory.baseline?.freecadVersion !== '1.1.1' || inventory.baseline?.commit !== '0108fd4b4850cc46e625b60e53cea7a7bbe69f8d') fail('baseline mismatch.')
const statuses = new Set(['exact', 'compatible', 'read-only', 'experimental', 'unsupported'])
const strategies = new Set(['native-parser', 'occt-worker', 'worker-adapter', 'sanitized-parser', 'server-export', 'sandboxed-adapter', 'proxy-resource', 'facade-parser', 'sandboxed-interpreter', 'blocked-resource', 'signed-catalog', 'namespaced-settings', 'browser-clipboard-permission'])
const validate = (entries, label) => {
  if (!Array.isArray(entries) || entries.length === 0) fail(`${label} must not be empty.`)
  const ids = new Set()
  for (const entry of entries) {
    if (!entry.id || ids.has(entry.id) || !Array.isArray(entry.modules) || entry.modules.length === 0 || !Array.isArray(entry.sourceEvidence) || entry.sourceEvidence.length === 0) fail(`${label} contains an incomplete or duplicate entry.`)
    ids.add(entry.id)
    if (!strategies.has(entry.webStrategy) || !statuses.has(entry.compatibility)) fail(`${entry.id} lacks a declared Web strategy/compatibility level.`)
    for (const evidence of entry.sourceEvidence) if (evidence.startsWith('src/') && !evidence.includes('PreferencePages')) {
      access(resolve(root, '.cache/freecad/FreeCAD', evidence)).catch(() => fail(`${entry.id} source evidence is unavailable: ${evidence}`))
    }
  }
}
validate(inventory.formats, 'formats')
validate(inventory.entrypoints, 'entrypoints')
if (!Array.isArray(inventory.moduleCoverage) || inventory.moduleCoverage.length !== 34) fail('module coverage must enumerate all 34 modules.')
if (inventory.moduleCoverage.some((entry) => !entry.name || !entry.sourcePath || !['entrypoint-covered', 'scope-only'].includes(entry.status))) fail('module coverage contains an invalid entry.')
if (inventory.policy?.untrustedContent !== 'never-execute' || inventory.policy?.unknownOrUnlistedEntries !== 'fail-inventory-check') fail('unsafe entrypoint policy is missing.')
console.log(JSON.stringify({ status: 'entrypoint-inventory-pass', formatCount: inventory.formats.length, entrypointCount: inventory.entrypoints.length, moduleCount: inventory.moduleCoverage.length, unsupportedCount: [...inventory.formats, ...inventory.entrypoints].filter((entry) => entry.compatibility === 'unsupported').length }, null, 2))
