import { readFile, writeFile } from 'node:fs/promises'

const root = new URL('../', import.meta.url)
const [core, ui, entry] = await Promise.all([
  readFile(new URL('src/timer-core.js', root), 'utf8'),
  readFile(new URL('src/client-ui.js', root), 'utf8'),
  readFile(new URL('src/client-entry.js', root), 'utf8'),
])

// The client bundle is one CJS factory: strip module syntax from the pure core
// and inline it so the tested source is exactly what the browser runs.
const coreBody = core.replace(/^export /gm, '')
if (/^\s*export\s/m.test(coreBody)) {
  throw new Error('timer-core.js still contains an unsupported export form')
}
if (!entry.includes('/* __CORE__ */') || !entry.includes('/* __UI__ */')) {
  throw new Error('client-entry.js is missing a build marker')
}

const output = entry
  .replace('/* __CORE__ */', coreBody.trim())
  .replace('/* __UI__ */', ui.trim())
if (output.includes('/* __CORE__ */') || output.includes('/* __UI__ */')) {
  throw new Error('build markers were not replaced')
}

await writeFile(new URL('client.js', root), `${output.trim()}\n`)
console.log(`built client.js (${output.length} bytes)`)
