#!/usr/bin/env node
/** Setzt nur ß→ss Overrides in de-CH.json, ohne bestehende Einträge zu löschen. */

const fs = require('fs');
const path = require('path');

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

function flatten(obj, prefix = '', out = {}) {
  for (const [key, value] of Object.entries(obj || {})) {
    const nextKey = prefix ? `${prefix}.${key}` : key;
    if (value && typeof value === 'object' && !Array.isArray(value)) {
      flatten(value, nextKey, out);
    } else if (typeof value === 'string') {
      out[nextKey] = value;
    }
  }
  return out;
}

function setByPath(obj, dotPath, value) {
  const parts = dotPath.split('.');
  let cur = obj;
  for (let i = 0; i < parts.length - 1; i++) {
    if (!cur[parts[i]] || typeof cur[parts[i]] !== 'object') cur[parts[i]] = {};
    cur = cur[parts[i]];
  }
  cur[parts[parts.length - 1]] = value;
}

const de = JSON.parse(fs.readFileSync(path.join(LOCALES_DIR, 'de.json'), 'utf8'));
const deFlat = flatten(de);
const chPath = path.join(LOCALES_DIR, 'de-CH.json');
const ch = JSON.parse(fs.readFileSync(chPath, 'utf8'));
const chFlat = flatten(ch);

let n = 0;
for (const [key, deVal] of Object.entries(deFlat)) {
  if (!deVal.includes('ß')) continue;
  const swiss = deVal.replace(/ß/g, 'ss');
  if (chFlat[key] !== swiss) {
    setByPath(ch, key, swiss);
    n++;
  }
}

fs.writeFileSync(chPath, `${JSON.stringify(ch, null, 2)}\n`, 'utf8');
console.log(`de-CH: ${n} ß→ss patches applied`);
