const e=`#!/usr/bin/env node
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname } from 'node:path';

function die(message) {
  process.stderr.write('Error: ' + message + '
');
  process.exit(1);
}

function parseArgs(argv) {
  const args = { template: null, data: null, out: null, id: null };

  for (let index = 2; index < argv.length; index += 1) {
    const arg = argv[index];

    if (arg === '--template' || arg === '--data' || arg === '--out' || arg === '--id') {
      const value = argv[index + 1];

      if (!value || value.startsWith('--')) {
        die(arg + ' requires a value');
      }

      args[arg.slice(2)] = value;
      index += 1;
      continue;
    }

    die('Unknown argument: ' + arg + '. Usage: node scripts/inject-viewer.mjs --template <html> --data <json> --out <output.html> [--id <placeholder-id>]');
  }

  if (!args.template) {
    die('--template is required');
  }

  if (!args.data) {
    die('--data is required');
  }

  if (!args.out) {
    die('--out is required');
  }

  return args;
}

function escapeRegExp(value) {
  return value.replace(/[|\\\\{}()\\[\\]^$+*?.]/g, '\\\\$&');
}

function buildScriptPattern(id) {
  const typeLookahead = "(?=[^>]*\\btype=['"]application\\/json['"] )".replace(' )', ')');
  const idLookahead = id
    ? ("(?=[^>]*\\bid=['"]" + escapeRegExp(id) + "['"] )").replace(' )', ')')
    : "(?=[^>]*\\bid=['"][^'"]+['"] )".replace(' )', ')');

  return new RegExp(
    '(<script\\b' + typeLookahead + idLookahead + '[^>]*>)[\\s\\S]*?(<\/script>)',
    'i',
  );
}

const args = parseArgs(process.argv);

let template;
try {
  template = readFileSync(args.template, 'utf8');
} catch (error) {
  die('Cannot read template: ' + args.template + ' - ' + error.message);
}

let data;
try {
  data = readFileSync(args.data, 'utf8');
} catch (error) {
  die('Cannot read data: ' + args.data + ' - ' + error.message);
}

try {
  JSON.parse(data);
} catch (error) {
  die('Invalid JSON in ' + args.data + ': ' + error.message);
}

const pattern = buildScriptPattern(args.id);
if (!pattern.test(template)) {
  if (args.id) {
    die('No <script type="application/json" id="' + args.id + '"> found in template');
  }

  die('No <script type="application/json" id="..."> found in template');
}

const safeData = data.replace(/<\\/script/gi, '<\\/script');
const output = template.replace(pattern, '$1
' + safeData + '
$2');

try {
  mkdirSync(dirname(args.out), { recursive: true });
  writeFileSync(args.out, output, 'utf8');
} catch (error) {
  die('Cannot write output: ' + args.out + ' - ' + error.message);
}

process.stdout.write('Injected ' + args.data + ' -> ' + args.out + '
');
`;export{e as INJECT_VIEWER_SCRIPT};