import path from 'path';
import { getDirname } from '../../../../utils/dirname-from-import-meta.util';
import { configChangeAlertDeps } from './setup-config-change-alert.constant';
import { setupAlert } from '../setup-alert/setup-alert.helper';
import { SetupConfigChangeAlertArgs } from './setup-config-change-alert.type';

const dirname = getDirname(import.meta);

export const setupConfigChangeAlert = async ({
  alertName,
  monitoredFile,
  monitoredCommand,
}: SetupConfigChangeAlertArgs) => {
  const config = await (await import('../../../config/config.helper')).loadConfig();
  const healthdPath = config?.healthdPath;
  const healthScriptsPath = config?.healthScriptsPath;
  if (!healthdPath || !healthScriptsPath) {
    throw new Error(
      'healthdPath and healthScriptsPath must be set in config before calling setupConfigChangeAlert.',
    );
  }
  const baseAlertDir = path.join(healthScriptsPath, alertName);
  const scriptPath = `${baseAlertDir}/update-${alertName}-status.sh`;
  const hashFilePath = `${baseAlertDir}/${alertName}.status.hash`;
  const statsdChartPath = `${baseAlertDir}/${alertName}.statsd.conf`;
  const healthAlertPath = path.join(healthdPath, `${alertName}.conf`);
  const scriptDir = path.join(dirname);

  const metricName = `${alertName.replace(/_/g, '.')}.changed`;

  let scriptReplacements: Record<string, string> = {
    __HASH_FILE__: hashFilePath,
    __METRIC_NAME__: metricName,
  };
  if (monitoredFile) {
    scriptReplacements[
      'MONITORED_FILE="__MONITORED_FILE__"'
    ] = `MONITORED_FILE='${monitoredFile}'`;
  } else if (monitoredCommand) {
    scriptReplacements[
      'MONITORED_COMMAND="__MONITORED_COMMAND__"'
    ] = `MONITORED_COMMAND='${monitoredCommand}'`; // important to use single quotes in case the command contains double quotes
  } else {
    throw new Error(
      'monitoredFile or monitoredCommand must be set in config before calling setupConfigChangeAlert.',
    );
  }

  await setupAlert({
    alertName,
    dependencies: configChangeAlertDeps,
    templates: [
      {
        templatePath: path.join(
          scriptDir,
          'update-config-change-status.template.sh',
        ),
        destinationPath: scriptPath,
        replacements: scriptReplacements,
        mode: 0o755,
      },
      {
        templatePath: path.join(scriptDir, 'config-change-alert.template.conf'),
        destinationPath: healthAlertPath,
        replacements: {
          __ALERT_NAME__: alertName,
          __ON__: `statsd_${metricName}_gauge`,
        },
      },
    ],
    cronScriptPath: scriptPath,
    healthdPath,
    healthScriptsPath,
    checkFiles: [statsdChartPath, healthAlertPath],
  });
};
