#!/usr/bin/env node
// Copyright (C) 2026 Garudex Labs.  All Rights Reserved.
// Caracal, a product of Garudex Labs
//
// Writes apps/tui/src/version.gen.ts with the dev, rc, or stable TUI identity.

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

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

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'

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 TUI identity. Generated by scripts/stampDev.mjs in dev or scripts/stampRelease.mjs in CI.

export const CARACAL_TUI_VERSION = '${version}'
export const CARACAL_TUI_MODE: 'dev' | 'rc' | 'stable' = '${mode}'
export const CARACAL_TUI_SHA = '${sha}'
`

writeFileSync(resolve(tuiRoot, 'src/version.gen.ts'), body, 'utf8')
process.stdout.write(`stamped ${mode} TUI version ${version}\n`)
