#!/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, rc, or stable CLI identity.

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 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'
  }
}

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

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

if (ciRelease && /(^|[+-])dev\./.test(ciRelease)) {
  process.stderr.write(`stampRelease: refusing dev-suffixed CARACAL_RELEASE_VERSION '${ciRelease}'\n`)
  process.exit(1)
}

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(`stamped ${mode} version ${version} registry ${registry}\n`)
