/**
 * 在外部配置文件追加用于追踪版本的信息
 */
import { GLOB_CONFIG_FILE_NAME, OUTPUT_DIR } from '../constant';
import fs, { appendFileSync } from 'fs-extra';
import { execSync } from 'node:child_process';
import colors from 'picocolors';

import { getRootPath } from '../utils';

import pkg from '../../package.json';
import dayjs from 'dayjs';

interface CreateTagParams {
  configFileName?: string;
}

function createTag(params: CreateTagParams) {
  const { configFileName } = params;
  try {
    const prop = '__LAST_PRODUCTION_TAG__';
    const path = `window.${prop}`;
    const tag = {
      // last commit's SHA
      commit: execSync('git rev-parse --short HEAD').toString().replace('\n', ''),
      buildtime: dayjs().format('YYYY-MM-DD_HH:mm:ss'),
    };
    // Ensure that the variable will not be modified
    const evalExp = `
      ${path}=${JSON.stringify(tag)};
      Object.freeze(${path});
      Object.defineProperty(window, "${prop}", {
        configurable: false,
        writable: false,
      });`.replace(/\s/g, '');

    fs.mkdirp(getRootPath(OUTPUT_DIR));
    appendFileSync(getRootPath(`${OUTPUT_DIR}/${configFileName}`), evalExp);

    console.log(colors.cyan(`✨ [${pkg.name}]`) + ` - tag infomation generate successfully:`);
    console.log(colors.gray(OUTPUT_DIR + '/' + colors.green(configFileName)) + '\n');
  } catch (error) {
    console.log(colors.red('tag infomation generation failed to package:\n' + error));
  }
}

export function runBuildTag() {
  createTag({
    configFileName: GLOB_CONFIG_FILE_NAME,
  });
}