import { execFileSync } from 'node:child_process'
import { access, cp, mkdir, readFile, rm, writeFile } from 'node:fs/promises'
import { resolve } from 'node:path'

const root = resolve(new URL('..', import.meta.url).pathname)
const source = resolve(root, 'OpenCAMLib')
const build = resolve(root, '.cache/opencamlib-wasm')
const boost = resolve(root, '.cache/opencamlib-boost')
const install = resolve(root, 'public/vendor/opencamlib')
const offlineBoost = resolve(root, '.cache/offline-sysroot/include/boost')
const systemBoost = process.env.BOOST_INCLUDE_DIR
  ? resolve(process.env.BOOST_INCLUDE_DIR, 'boost')
  : '/usr/include/boost'
const revision = execFileSync('git', ['-C', source, 'rev-parse', 'HEAD'], { encoding: 'utf8' }).trim()

await rm(boost, { recursive: true, force: true })
await mkdir(boost, { recursive: true })
await cp(await access(offlineBoost).then(() => offlineBoost, () => systemBoost), resolve(boost, 'boost'), { recursive: true })
await mkdir(build, { recursive: true })

const configure = [
  'cmake', '-S', source, '-B', build,
  '-D', 'BUILD_EMSCRIPTEN_LIB=ON',
  '-D', 'BUILD_CXX_LIB=OFF',
  '-D', 'BUILD_PY_LIB=OFF',
  '-D', 'BUILD_NODEJS_LIB=OFF',
  '-D', 'BUILD_DOC=OFF',
  '-D', 'USE_OPENMP=OFF',
  '-D', 'CMAKE_BUILD_TYPE=Release',
  '-D', `CMAKE_INSTALL_PREFIX=${install}`,
  '-D', `Boost_INCLUDE_DIR=${boost}`,
  '-D', 'Boost_NO_SYSTEM_PATHS=ON',
  '-D', `VERSION_STRING=${revision.slice(0, 16)}`,
]
execFileSync('emcmake', configure, { cwd: root, stdio: 'inherit' })

// The Debian Emscripten package omits the executable used only for optional JS minification.
const linkPath = resolve(build, 'src/CMakeFiles/ocl.dir/link.txt')
const originalLink = await readFile(linkPath, 'utf8')
const reproducibleLink = originalLink.replace(/\s+--closure\s+1\b/, '')
if (reproducibleLink === originalLink) throw new Error('OpenCAMLib generated link command did not contain the expected optional Closure flag.')
await writeFile(linkPath, reproducibleLink)
execFileSync('cmake', ['--build', build, '--target', 'ocl', '--parallel', '4'], { cwd: root, stdio: 'inherit' })
// Normalize the generated single-file loader before it becomes the public
// artifact. This removes Emscripten's version-sensitive whitespace-only line.
execFileSync('perl', ['-pi', '-e', 's/[ \\t]+$//', resolve(build, 'ocl.js')])
execFileSync('cmake', ['--install', build], { cwd: root, stdio: 'inherit' })
console.log(`Built OpenCAMLib ${revision} into ${install}`)
