#!/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-stamped TUI identity and prints the short SHA on stdout.

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 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 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(`${releaseVersion ?? sha}\n`)
