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

const root = resolve(new URL('..', import.meta.url).pathname)
const load = async (path) => JSON.parse(await readFile(resolve(root, path), 'utf8'))
const [abi, matrix, plan, readiness, sdkPlan, nextTasks, nodeReport, chromeReport, packageJson, buildScript, smokeTest] = await Promise.all([
  load('config/freecad-sketcher-partdesign-abi-contract.json'),
  load('config/compatibility-matrix.json'),
  load('config/freecad-web-exact-parity-plan.json'),
  load('config/freecad-private-naming-source-readiness.json'),
  load('config/freecad-naming-sdk-plan.json'),
  load('config/freecad-naming-next-tasks.json'),
  load('config/freecad-naming-production-verification.json'),
  load('config/chrome-freecad-naming-production-verification.json'),
  load('package.json'),
  readFile(resolve(root, 'native/occt-history/build.sh'), 'utf8'),
  readFile(resolve(root, 'native/freecad-naming-probe/smoke-test.mjs'), 'utf8'),
])
const fail = (message) => { throw new Error(`FreeCAD private naming boundary: ${message}`) }
const callbacks = ['freecadNamingAbiVersion', 'freecadNamingCapabilitiesJson', 'freecadNamingEvidenceJson']
const operations = ['fuse', 'cut', 'common', 'rotate', 'pad', 'pocket', 'loft', 'pipe', 'revolution', 'groove', 'fillet', 'chamfer', 'hole', 'draft', 'thickness', 'linear-pattern', 'polar-pattern', 'mirrored', 'multi-transform']

const tasks = plan.programs.flatMap((program) => program.tasks)
const task = tasks.find((entry) => entry.id === 'EX-TSN-02')
if (!task) fail('EX-TSN-02 is missing from the exact parity plan.')
if (abi.privateNamingAbi?.shippedWorkerImplementation !== 'freecad-linked') fail('the shipped ABI contract must identify the verified FreeCAD-linked Worker.')
if (abi.claim?.exactFreeCadParity !== false || matrix.systemExactEvaluation?.exact !== false) fail('production linkage cannot promote system exactness.')
if (matrix.nativeOcctHistory?.freecadNamingBuild?.status !== 'production-linked') fail('the FreeCAD naming build status must identify production linkage.')
if (matrix.nativeOcctHistory?.freecadNamingBuild?.prerequisiteStatus !== 'real-isolated-freecad-private-naming-bridge-pass') fail('the prerequisite status must identify the real isolated FreeCAD naming bridge.')
if (matrix.nativeOcctHistory?.freecadNamingBuild?.sdkReadinessStatus !== 'candidate-complete') fail('the SDK readiness status must retain the complete SDK prerequisite.')
if (task.status !== 'completed' || task.exactBlockedBy?.length !== 0) fail(`EX-TSN-02 must be completed and blocker-free, received ${String(task.status)}.`)
const blockers = matrix.systemExactEvaluation?.blockers ?? []
if (blockers.length !== 2 || blockers.some((blocker) => blocker.includes('lacks the FreeCAD-linked') || blocker.includes('browser builder naming evidence transport') || blocker.includes('non-unique isomorphic'))) fail('system exact blockers must remove the closed Worker linkage, browser transport and isomorphic provenance gaps.')

for (const [label, report, runtime] of [['Node', nodeReport, 'node'], ['Chrome', chromeReport, 'chrome']]) {
  if (report.status !== 'pass' || report.runtime !== runtime || report.implementation !== 'freecad-linked' || report.productionWorkerLinked !== true || report.systemExact !== false) fail(`${label} production report has an invalid boundary.`)
  if (JSON.stringify(report.callbacks) !== JSON.stringify(callbacks) || JSON.stringify(report.operations) !== JSON.stringify(operations) || report.cases?.length !== operations.length) fail(`${label} production report does not cover all callbacks and builders.`)
  if (report.cases.some((entry, index) => entry.operation !== operations[index] || entry.status !== 'pass' || entry.provenanceResults !== entry.selectedRecords + entry.ambiguousResults || entry.provenanceResults < 1 || entry.mappedNames !== entry.selectedRecords || entry.callbackExecuted !== (entry.selectedRecords > 0) || (entry.selectedRecords > 0 ? entry.elementMaps < 1 : entry.namingStatus !== 'ambiguous'))) fail(`${label} production report contains incomplete provenance evidence.`)
  if (report.isomorphicCorpus?.status !== 'pass' || report.isomorphicCorpus.uniqueResults !== 0 || report.isomorphicCorpus.ambiguousResults < 1 || report.isomorphicCorpus.arrayOrderFallbackUsed !== false) fail(`${label} production report lacks symmetric ambiguity evidence.`)
  if (report.invalidHistoryRejected !== true || report.chainedStage?.stringHasherEntries < 2 || report.artifacts?.length !== 3) fail(`${label} production report lacks chained, fail-closed or artifact evidence.`)
}

if (readiness.scope !== 'standalone-wasm-source-prerequisite') fail('source readiness must remain a standalone prerequisite, not a production implementation.')
if (sdkPlan.scope !== 'pre-production-sdk-readiness' || sdkPlan.productionPublication !== false) fail('SDK readiness must remain non-publishing even after the Worker is published by its own build.')
if (sdkPlan.boundary?.freecadNamingBuildStatus !== 'production-linked' || sdkPlan.boundary?.exTsn02 !== 'completed' || sdkPlan.boundary?.systemExact !== false) fail('SDK readiness boundary disagrees with the authoritative status files.')
if (nextTasks.boundary?.freecadNamingBuildStatus !== 'production-linked' || nextTasks.boundary?.exTsn02 !== 'completed' || nextTasks.boundary?.systemExact !== false || nextTasks.boundary?.productionWorker?.availability !== 'available' || JSON.stringify(nextTasks.boundary.productionWorker.callbacks) !== JSON.stringify(callbacks)) fail('next-task plan disagrees with the production boundary.')
if (readiness.production?.workerLinked !== true || JSON.stringify(readiness.production?.exportedCallbacks) !== JSON.stringify(callbacks)) fail('the readiness manifest must record the linked production callbacks.')
if (readiness.boundary?.freecadNamingBuildStatus !== 'production-linked' || readiness.boundary?.exTsn02 !== 'completed' || readiness.boundary?.systemExact !== false) fail('the readiness manifest boundary disagrees with the authoritative status files.')
if (readiness.candidateAbi?.scope !== 'isolated-non-production' || readiness.candidateAbi?.occtBuilderContext !== false || readiness.candidateAbi?.publishToWorker !== false) fail('the candidate ABI must remain isolated and non-publishing.')
if (readiness.isolatedSourceArchive?.target !== 'wasm32-emscripten' || readiness.isolatedSourceArchive?.expectedObjectMembers !== 7 || readiness.isolatedSourceArchive?.hostAdapterBound !== true || readiness.isolatedSourceArchive?.productionEligible !== false) fail('the source archive must remain a seven-object, host-adapter-bound wasm prerequisite.')
if (readiness.candidateAbi?.strictWebValidator !== 'pass') fail('the candidate ABI must pass the strict Web validator.')
for (const resource of ['MappedNameRef', 'StringHasher', 'ElementMap2']) if (!readiness.candidateAbi?.nativeResources?.includes(resource)) fail(`the candidate ABI must validate native ${resource} evidence.`)
for (const callback of readiness.candidateAbi?.exports ?? []) if (!callback.startsWith('freecadNamingCandidate')) fail(`candidate export ${callback} could be mistaken for a production callback.`)
for (const callback of callbacks) if (!smokeTest.includes(callback)) fail(`the isolated source smoke test must detect production callback ${callback}.`)
for (const component of ['FreeCADBase static library', 'FreeCADApp static library', 'Part static library', 'Python static library', 'FreeCAD private naming Worker bridge']) if (!readiness.productionLinkedComponents?.includes(component)) fail(`production linked components omit ${component}.`)
for (const component of ['complete Application and Document parity', 'exhaustive FCStd edit and round-trip corpus']) if (!readiness.remainingExactComponents?.includes(component)) fail(`remaining exact components omit ${component}.`)
if (readiness.remainingExactComponents?.includes('unique isomorphic topology provenance')) fail('closed isomorphic provenance remains listed as an exact component.')
if (!buildScript.includes('BITBYBIT_FREECAD_NAMING_LINKED=1') || !buildScript.includes('OCCT_HISTORY_PUBLISH')) fail('the Worker build does not enforce linked ABI compilation and explicit publication.')
if (!packageJson.scripts?.['build:occt-history']?.includes('FREECAD_WASM_NAMING_REQUIRED=1') || !packageJson.scripts['build:occt-history'].includes('OCCT_HISTORY_PUBLISH=1')) fail('the production build command does not fail closed on FreeCAD linkage and publication.')
if (!packageJson.scripts?.['build:occt-history-only-candidate']?.includes('OCCT_HISTORY_PUBLISH=0')) fail('the OCCT-only build must remain an explicitly non-publishing candidate.')

console.log(JSON.stringify({
  status: 'boundary-pass',
  shippedWorkerImplementation: 'freecad-linked',
  task: { id: task.id, status: task.status },
  systemExact: false,
  sdkStatus: matrix.nativeOcctHistory.freecadNamingBuild.status,
  callbacks,
  operations: operations.length,
  productionReports: { node: nodeReport.generatedAt, chrome: chromeReport.generatedAt },
  candidateAbi: { scope: readiness.candidateAbi.scope, strictWebValidator: readiness.candidateAbi.strictWebValidator, publishToWorker: readiness.candidateAbi.publishToWorker },
  sdkReadiness: { scope: sdkPlan.scope, productionPublication: sdkPlan.productionPublication, requiredLibraries: sdkPlan.libraries.map(({ name }) => name) },
}, null, 2))
