import { mkdir, readFile, writeFile } from 'node:fs/promises'
import { dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'

interface PackageJson {
  name: string
  version: string
}

const scriptDir = dirname(fileURLToPath(import.meta.url))
const cliRoot = resolve(scriptDir, '..')
const pkgPath = resolve(cliRoot, 'package.json')
const outPath = resolve(cliRoot, 'src/generated/pkg-info.ts')

const pkg = JSON.parse(await readFile(pkgPath, 'utf8')) as PackageJson

if (typeof pkg.name !== 'string' || typeof pkg.version !== 'string') {
  throw new Error(`package.json at ${pkgPath} is missing name or version`)
}

const contents =
  '// Generated by scripts/generate-pkg-info.ts - do not edit by hand.\n' +
  `export const PKG_NAME = ${JSON.stringify(pkg.name)}\n` +
  `export const PKG_VERSION = ${JSON.stringify(pkg.version)}\n`

await mkdir(dirname(outPath), { recursive: true })
await writeFile(outPath, contents, 'utf8')

console.log(`generated ${outPath}`)
