import { execSync } from 'node:child_process'
import { mkdirSync, writeFileSync } from 'node:fs'
import { dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'

const __dirname = dirname(fileURLToPath(import.meta.url))
const appRoot = resolve(__dirname, '..')
const outFile = resolve(appRoot, 'src/generated/commit-info.ts')

function readCommitCode() {
  try {
    return execSync('git rev-parse --short HEAD', {
      cwd: appRoot,
      stdio: ['ignore', 'pipe', 'ignore'],
      encoding: 'utf8'
    }).trim()
  } catch {
    return 'unknown'
  }
}

const commitCode = readCommitCode()
const content =
  `// Auto-generated by scripts/generate-commit-info.mjs\n` +
  `export const COMMIT_CODE = ${JSON.stringify(commitCode)} as const\n`

mkdirSync(dirname(outFile), { recursive: true })
writeFileSync(outFile, content, 'utf8')

console.log(`Generated commit info: ${commitCode}`)
