#!/usr/bin/env node
/** UK/AU-Orthografie in en-GB / en-AU (gegenüber en-US). */
const fs = require('fs');
const path = require('path');

const LOCALES_DIR = path.join(__dirname, '../frontend/src/i18n/locales');

const UK_MAP = [
  [/\bcolor\b/gi, (m) => (m[0] === 'C' ? 'Colour' : 'colour')],
  [/\bcolors\b/gi, (m) => (m[0] === 'C' ? 'Colours' : 'colours')],
  [/\borganize\b/gi, (m) => (m[0] === 'O' ? 'Organise' : 'organise')],
  [/\borganized\b/gi, (m) => (m[0] === 'O' ? 'Organised' : 'organised')],
  [/\bcenter\b/gi, (m) => (m[0] === 'C' ? 'Centre' : 'centre')],
  [/\bfavorite\b/gi, (m) => (m[0] === 'F' ? 'Favourite' : 'favourite')],
  [/\bfavorites\b/gi, (m) => (m[0] === 'F' ? 'Favourites' : 'favourites')],
  [/\blabor\b/gi, (m) => (m[0] === 'L' ? 'Labour' : 'labour')],
  [/\bdefense\b/gi, (m) => (m[0] === 'D' ? 'Defence' : 'defence')],
];

function applyUk(text) {
  let out = text;
  for (const [re, repl] of UK_MAP) {
    out = out.replace(re, repl);
  }
  return out;
}

function walk(obj, fn) {
  if (!obj || typeof obj !== 'object' || Array.isArray(obj)) return;
  for (const [key, value] of Object.entries(obj)) {
    if (typeof value === 'string') obj[key] = fn(value);
    else if (value && typeof value === 'object') walk(value, fn);
  }
}

for (const locale of ['en-GB', 'en-AU']) {
  const p = path.join(LOCALES_DIR, `${locale}.json`);
  const data = JSON.parse(fs.readFileSync(p, 'utf8'));
  let n = 0;
  walk(data, (s) => {
    const t = applyUk(s);
    if (t !== s) n++;
    return t;
  });
  fs.writeFileSync(p, `${JSON.stringify(data, null, 2)}\n`, 'utf8');
  console.log(`${locale}: ${n} UK spelling patches`);
}
