import { readFile } from 'node:fs/promises'
import { dirname, resolve } from 'node:path'
import { spawnSync } from 'node:child_process'

const root = resolve(new URL('..', import.meta.url).pathname)
const command = process.env.FREECAD_CMD || resolve(root, '.cache/freecad/install-native/bin/FreeCADCmd')
const driver = resolve(root, 'scripts/freecad-golden-driver.py')
const manifestArgument = process.argv.slice(2).find((argument) => argument.startsWith('--manifest='))
const manifestPath = resolve(root, manifestArgument?.slice('--manifest='.length) || 'fixtures/freecad-golden/failures/manifest.json')
const manifest = JSON.parse(await readFile(manifestPath, 'utf8'))
const reports = []
for (const entry of manifest.failures) {
  const fixture = resolve(dirname(manifestPath), entry.file)
  const execution = spawnSync(command, [driver], {
    cwd: root,
    encoding: 'utf8',
    timeout: 120000,
    maxBuffer: 2 * 1024 * 1024,
    env: { ...process.env, FREECAD_GOLDEN_SCENARIO: fixture },
  })
  const output = `${execution.stdout || ''}\n${execution.stderr || ''}`
  const exceptionCaptured = output.includes('Exception while processing file')
  const resultLine = output.split(/\r?\n/).find((line) => line.startsWith('FREECAD_GOLDEN_RESULT='))
  let invalidShape = false
  if (resultLine) {
    try {
      const result = JSON.parse(resultLine.slice('FREECAD_GOLDEN_RESULT='.length))
      invalidShape = result.isValid === false || result.volume <= 0
    } catch {
      invalidShape = false
    }
  }
  const passed = exceptionCaptured || invalidShape
  reports.push({ id: entry.id, passed, status: execution.status, exceptionCaptured, invalidShape })
}
console.log(JSON.stringify({ status: reports.every((report) => report.passed) ? 'freecad-golden-failures-pass' : 'freecad-golden-failures-fail', count: reports.length, reports }, null, 2))
if (reports.some((report) => !report.passed)) process.exit(1)
