#!/usr/bin/env node
// Copyright (C) 2026 Garudex Labs.  All Rights Reserved.
// Caracal, a product of Garudex Labs
//
// Writes apps/cli/src/runtime/version.gen.ts with the dev-stamped CLI identity and prints the short SHA on stdout.

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

const here = dirname(fileURLToPath(import.meta.url))
const cliRoot = resolve(here, '..')
const repoRoot = resolve(cliRoot, '..', '..')

function baseVersion() {
  const raw = readFileSync(resolve(repoRoot, 'packages/engine/runtime/release.json'), 'utf8')
  return JSON.parse(raw).version
}

function shortSha() {
  if (process.env.CARACAL_DEV_SHA) return process.env.CARACAL_DEV_SHA
  try {
    return execSync('git rev-parse --short HEAD', { cwd: repoRoot }).toString().trim()
  } catch {
    return 'nogit'
  }
}

const sha = shortSha()
const releaseVersion = process.env.CARACAL_RELEASE_VERSION
const version = releaseVersion ?? `${baseVersion()}-dev.sha${sha}`
const mode = releaseVersion ? (releaseVersion.includes('-rc.') ? 'rc' : 'stable') : 'dev'
const registry = releaseVersion ? 'ghcr.io/garudex-labs/' : 'localhost/'

const body =
  `// Copyright (C) 2026 Garudex Labs.  All Rights Reserved.
// Caracal, a product of Garudex Labs
//
// Stamped CLI identity. Generated by scripts/stampDev.mjs in dev or scripts/stampRelease.mjs in CI.

export const CARACAL_VERSION = '${version}'
export const CARACAL_MODE: 'dev' | 'rc' | 'stable' = '${mode}'
export const CARACAL_REGISTRY = '${registry}'
export const CARACAL_SHA = '${sha}'
`

const versionFile = resolve(cliRoot, 'src/runtime/version.gen.ts')
mkdirSync(dirname(versionFile), { recursive: true })
writeFileSync(versionFile, body, 'utf8')
process.stdout.write(`${releaseVersion ?? sha}\n`)
