import { readFileSync, writeFileSync } from 'fs';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';

const __dirname = dirname(fileURLToPath(import.meta.url));
const root = join(__dirname, '..');
const s = readFileSync(join(root, 'frontend/src/i18n/npcGeneratedNames.ts'), 'utf8');

function extractArray(constName) {
  const start = s.indexOf(`export const ${constName}`);
  if (start < 0) throw new Error('missing ' + constName);
  const slice = s.slice(start, start + 80000);
  const out = [];
  const re = /en: '((?:\\'|[^'])*)'/g;
  let m;
  let depth = 0;
  const subStart = slice.indexOf('[');
  const subEnd = slice.indexOf('];', subStart);
  const block = slice.slice(subStart, subEnd);
  while ((m = re.exec(block))) {
    out.push(m[1].replace(/\\'/g, "'"));
  }
  return out;
}

const elder = extractArray('ELDER_GEN_NAMES');
const medic = extractArray('MEDIC_GEN_NAMES');
const stall = extractArray('STALL_GEN_NAMES');

function sqlArr(a) {
  return `ARRAY[${a.map((x) => `'${x.replace(/'/g, "''")}'`).join(',')}]::text[]`;
}

const sql =
  `-- Generated by scripts/gen-npc-sql-arrays.mjs from npcGeneratedNames.ts\n` +
  `-- lengths: elder=${elder.length} medic=${medic.length} stall=${stall.length}\n` +
  `elder_names text[] := ${sqlArr(elder)};\n` +
  `medic_names text[] := ${sqlArr(medic)};\n` +
  `stall_names text[] := ${sqlArr(stall)};\n`;

writeFileSync(join(root, 'scripts/_npc_name_arrays_snippet.sql'), sql);
console.log('Wrote scripts/_npc_name_arrays_snippet.sql', elder.length, medic.length, stall.length);
