/*
 * Copyright Elasticsearch B.V. and contributors
 * SPDX-License-Identifier: Apache-2.0
 */

const fs = require('fs')
const path = require('path')

const rootDir = path.join(__dirname, '..')
const clientPkg = JSON.parse(fs.readFileSync(path.join(rootDir, 'package.json'), 'utf8'))
let transportVersion = '0.0.0'
try {
  const transportPkgPath = require.resolve('@elastic/transport/package.json', { paths: [rootDir] })
  const transportPkg = JSON.parse(fs.readFileSync(transportPkgPath, 'utf8'))
  transportVersion = transportPkg.version
} catch (_) {
  // @elastic/transport not installed (e.g. pre-install); use placeholder 0.0.0
}

const outPath = path.join(rootDir, 'src', 'version.generated.ts')
const content = `/*
 * Copyright Elasticsearch B.V. and contributors
 * SPDX-License-Identifier: Apache-2.0
 *
 * Generated by scripts/generate-version.js - do not edit manually.
 */

export const clientVersion: string = '${clientPkg.version}'
export const transportVersion: string = '${transportVersion}'
`

fs.writeFileSync(outPath, content, 'utf8')
console.log(`Generated ${outPath} (client: ${clientPkg.version}, transport: ${transportVersion})`)
