import { spawnSync } from 'node:child_process'
import { existsSync } from 'node:fs'
import { writeFile } from 'node:fs/promises'
import { resolve } from 'node:path'

const root = resolve(new URL('..', import.meta.url).pathname)
const executable = process.env.FREECAD_CMD || resolve(root, '.cache/freecad/install-desktop/bin/FreeCADCmd')
const sysroot = resolve(root, '.cache/freecad/sysroot')
const script = resolve(root, 'scripts/freecad-tsn-stage-correlation-oracle.py')
const outputPath = resolve(root, 'config/freecad-tsn-stage-correlation-oracle.json')
if (!existsSync(executable)) throw new Error(`FreeCAD TSN stage-correlation executable is missing: ${executable}`)
const execution = spawnSync(executable, ['--python-path', resolve(sysroot, 'usr/lib/python3/dist-packages'), script], {
  cwd: root,
  encoding: 'utf8',
  timeout: 180_000,
  maxBuffer: 40 * 1024 * 1024,
  env: {
    ...process.env,
    PYTHONPATH: `${resolve(sysroot, 'usr/lib/python3/dist-packages')}${process.env.PYTHONPATH ? `:${process.env.PYTHONPATH}` : ''}`,
    LD_LIBRARY_PATH: `${resolve(sysroot, 'usr/lib/x86_64-linux-gnu')}${process.env.LD_LIBRARY_PATH ? `:${process.env.LD_LIBRARY_PATH}` : ''}`,
    MATPLOTLIBRC: resolve(sysroot, 'usr/share/matplotlib/mpl-data/matplotlibrc'),
    MPLBACKEND: 'Agg',
  },
})
const output = `${execution.stdout || ''}\n${execution.stderr || ''}`
const marker = 'FREECAD_TSN_STAGE_CORRELATION_RESULT='
const markerIndex = output.indexOf(marker)
if (execution.error || execution.status !== 0 || markerIndex < 0) throw new Error(`FreeCAD TSN stage-correlation oracle failed with status ${execution.status}: ${execution.error?.message || output.trim()}`)
const resultLine = output.slice(markerIndex + marker.length).split(/\r?\n/, 1)[0]
const report = JSON.parse(resultLine)
if (report.status !== 'pass') throw new Error(`FreeCAD TSN stage-correlation oracle reported ${report.status}: ${report.error || 'unknown failure'}`)
await writeFile(outputPath, `${JSON.stringify(report, null, 2)}\n`)
console.log(JSON.stringify({ status: 'freecad-tsn-stage-correlation-generated', ...report.summary, exactCorrelationReady: report.exactCorrelationReady }, null, 2))
