#!/usr/bin/env node
// Gera src/build-info.js com SHA + version do package.json + URL GitLab.
// Roda no `predev` e `prebuild` do @ufpe/docs.

import { execSync } from 'node:child_process';
import { readFile, writeFile } from 'node:fs/promises';
import { resolve, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';

const __dirname = dirname(fileURLToPath(import.meta.url));
const APP_ROOT = resolve(__dirname, '..');
const REPO_ROOT = resolve(APP_ROOT, '../..');

const REPO_URL = 'https://gitlab.ufpe.br/thiago.prazeres/design-system-sti-ufpe';

const sh = (cmd) => { try { return execSync(cmd, { cwd: REPO_ROOT }).toString().trim(); } catch { return null; } };

const sha    = sh('git rev-parse --short HEAD') ?? 'dev';
const tag    = sh('git describe --tags --exact-match 2>/dev/null') ?? null;
const branch = sh('git rev-parse --abbrev-ref HEAD') ?? 'master';
const dirty  = sh('git status --porcelain').length > 0;

const pkg = JSON.parse(await readFile(resolve(REPO_ROOT, 'package.json'), 'utf8'));

const info = {
  version: pkg.version,
  tag,
  sha,
  branch,
  dirty,
  repo: REPO_URL,
  commitUrl: `${REPO_URL}/-/commit/${sha}`,
  tagUrl: tag ? `${REPO_URL}/-/tags/${tag}` : null,
  builtAt: new Date().toISOString(),
};

await writeFile(
  resolve(APP_ROOT, 'src/build-info.js'),
  `// Generated by scripts/generate-build-info.js — do not edit.\nexport default ${JSON.stringify(info, null, 2)};\n`,
);

console.log(`✓ build-info: ${info.tag || info.version}@${sha}${dirty ? ' (dirty)' : ''}`);
