import { readFileSync, writeFileSync, mkdirSync } from 'node:fs'
import { createRequire } from 'node:module'
import { dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'

const requireCjs = createRequire(import.meta.url)

const enginePath = requireCjs.resolve('web-tree-sitter/web-tree-sitter.wasm')
const grammarPath = requireCjs.resolve('tree-sitter-bash/tree-sitter-bash.wasm')

const engine = readFileSync(enginePath).toString('base64')
const grammar = readFileSync(grammarPath).toString('base64')

const outDir = resolve(dirname(fileURLToPath(import.meta.url)), '..', 'src', 'generated')
mkdirSync(outDir, { recursive: true })

const contents = `// generated by scripts/embed-wasm.mjs — do not edit
export const ENGINE_WASM_BASE64 = ${JSON.stringify(engine)}
export const GRAMMAR_WASM_BASE64 = ${JSON.stringify(grammar)}
`

writeFileSync(resolve(outDir, 'wasm.ts'), contents)
console.log(
  `embedded ${(engine.length / 1024).toFixed(0)}KB engine + ${(grammar.length / 1024).toFixed(0)}KB grammar (base64)`,
)
