import { readFileSync } from 'node:fs'
import * as esbuild from 'esbuild'
import { fileURLToPath } from 'node:url'
import path from 'node:path'

const rootDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
const packageJson = JSON.parse(
  readFileSync(path.join(rootDir, 'package.json'), 'utf8')
)

let buildNumber = process.env.BUILD_NUMBER || process.env.VITE_BUILD_NUMBER || 'dev'
try {
  const buildInfo = JSON.parse(
    readFileSync(path.join(rootDir, 'src/buildInfo.json'), 'utf8')
  )
  buildNumber = buildInfo.buildNumber ?? buildNumber
} catch {}

await esbuild.build({
  entryPoints: [path.join(rootDir, 'src/headless.js')],
  bundle: true,
  platform: 'node',
  target: 'node18',
  format: 'cjs',
  outfile: path.join(rootDir, 'build/pkg-entry.cjs'),
  external: [
    'electron',
    'sharp',
    'canvas',
    '@napi-rs/canvas',
    'pdf-to-img',
    'pdfjs-dist'
  ],
  inject: [path.join(rootDir, 'scripts/import-meta-url.js')],
  define: {
    'import.meta.url': 'import_meta_url',
    'process.env.FC_PACKAGE_VERSION': JSON.stringify(packageJson.version),
    'process.env.FC_BUILD_NUMBER': JSON.stringify(buildNumber)
  },
  logLevel: 'info'
})
