#!/usr/bin/env node
/**
 * Aktualisiert Kennzahlen-Tabellen in frontend/I18N_TODO.md aus check-i18n-completeness.
 * Usage: node scripts/update-i18n-todo-stats.js
 */

const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');

const ROOT = path.resolve(__dirname, '..');
const TODO = path.join(ROOT, 'frontend', 'I18N_TODO.md');

const LOCALES = [
  'de-CH',
  'de-extended',
  'en-US',
  'en-GB',
  'en-AU',
  'es',
  'fr',
  'it',
  'pl',
  'ja',
  'zh',
  'th',
  'tl',
  'fil',
];

function parseStats() {
  const out = execSync(`node "${path.join(__dirname, 'check-i18n-completeness.js')}"`, {
    cwd: ROOT,
    encoding: 'utf8',
  });
  const stats = {};
  for (const line of out.split('\n')) {
    const m = line.match(/^(\S+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/);
    if (m && LOCALES.includes(m[1])) {
      stats[m[1]] = {
        explicit: m[2],
        erbtsDE: m[3],
        deExpl: m[4],
        neDe: m[5],
        enUs: m[6],
      };
    }
  }
  return stats;
}

function replaceTable(md, locale, row) {
  const header = `## \`${locale}\``;
  const idx = md.indexOf(header);
  if (idx === -1) return md;
  const tableStart = md.indexOf('| explicit |', idx);
  const tableEnd = md.indexOf('\n\n### Aufgaben', tableStart);
  if (tableStart === -1 || tableEnd === -1) return md;
  const newTable = `| explicit | erbtsDE | =de expl | ≠de | ≈en-US |
|----------|---------|----------|-----|--------|
| ${row.explicit} | ${row.erbtsDE} | ${row.deExpl} | ${row.neDe} | ${row.enUs} |`;
  return md.slice(0, tableStart) + newTable + md.slice(tableEnd);
}

function main() {
  const stats = parseStats();
  let md = fs.readFileSync(TODO, 'utf8');
  const date = new Date().toISOString().slice(0, 10);
  md = md.replace(
    /Stand der Kennzahlen: \*\*[\d-]+\*\*/,
    `Stand der Kennzahlen: **${date}**`
  );
  for (const locale of LOCALES) {
    if (stats[locale]) md = replaceTable(md, locale, stats[locale]);
  }
  fs.writeFileSync(TODO, md, 'utf8');
  console.log('Updated', TODO, 'for', Object.keys(stats).length, 'locales');
}

main();
