#!/usr/bin/env node

/**
 * Generate version information for the build
 * Captures git hash, build timestamp, and version
 */

/* eslint-env node */

import { execSync } from 'child_process';
import { writeFileSync, mkdirSync } from 'fs';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import process from 'process';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

try {
  // Get git information
  const gitHash = execSync('git rev-parse --short HEAD', { encoding: 'utf-8' }).trim();
  const gitBranch = execSync('git rev-parse --abbrev-ref HEAD', { encoding: 'utf-8' }).trim();

  // Get timestamp
  const buildTime = new Date().toISOString();

  // Read package.json version
  const packageJsonPath = join(__dirname, '..', 'package.json');
  const packageJson = JSON.parse(
    execSync(`cat ${packageJsonPath}`, { encoding: 'utf-8' })
  );

  const versionInfo = {
    version: packageJson.version,
    gitHash,
    gitBranch,
    buildTime,
    nodeVersion: process.version,
  };

  // Ensure public directory exists
  const publicDir = join(__dirname, '..', 'public');
  mkdirSync(publicDir, { recursive: true });

  // Write to public directory so it's accessible at runtime
  const outputPath = join(publicDir, 'version.json');
  writeFileSync(outputPath, JSON.stringify(versionInfo, null, 2));

  console.log('✅ Version information generated:');
  console.log(JSON.stringify(versionInfo, null, 2));

} catch (error) {
  console.error('⚠️  Failed to generate version info:', error.message);

  // Create fallback version info
  const fallbackVersion = {
    version: '0.0.0',
    gitHash: 'unknown',
    gitBranch: 'unknown',
    buildTime: new Date().toISOString(),
    nodeVersion: process.version,
  };

  // Ensure public directory exists
  const publicDir = join(__dirname, '..', 'public');
  mkdirSync(publicDir, { recursive: true });

  const outputPath = join(publicDir, 'version.json');
  writeFileSync(outputPath, JSON.stringify(fallbackVersion, null, 2));

  console.log('✅ Fallback version information generated');
}
